我已经安装了坚果包MvcSiteMapProvider.MVC5.DI.Autofac.Modules。我正在尝试将我的DBContext注册为InstancePerRequest。但是,如果出现错误,则失败。
No scope with a Tag matching 'AutofacWebRequest' is visible from the scope in which the instance was requested.如果我把DBContext换成InstancePerLifetimeScope,一切都会好起来的。错误将在文件中抛出。
DI\Autofac\Modules\MvcSiteMapProviderModule.cs Line: 195实际上,如果我尝试向InstancePerRequest注册我自己的任何类型,我就会得到这个错误。我是Autofac的新手,所以不能真正理解nuget包中用于MvcSiteMapProvider Autofac的很多代码。虽然我正在了解更多关于Autofac,希望有人能指出正确的方向,如何绕过这个问题?
编辑:
从Autofac文档中,我得到了错误,因为:
Code is running during application startup (e.g., in an ASP.NET Global.asax) that uses dependency resolution when there isn’t an active request yet.但是根据MvcSiteMapProvider文档,这一行是必需的,所以我可以把它移到其他地方吗?
// Setup global sitemap loader (required)
MvcSiteMapProvider.SiteMaps.Loader = container.Resolve<ISiteMapLoader>();编辑2:
protected void Application_Start()
{
// BEGIN: Autofac Config
var builder = new ContainerBuilder();
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterSource(new ViewRegistrationSource());
// Register context and unit of work here
IoC.Dependencies.Register.RegisterTypes(builder);
builder.RegisterModule(new MvcSiteMapProviderModule());
builder.RegisterModule(new MvcModule());
var container = builder.Build();
MvcSiteMapProvider.SiteMaps.Loader = container.Resolve<ISiteMapLoader>();
GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
// END: Autofac Config
Helpers.Log4NetManager.InitializeLog4Net();
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
}发布于 2015-09-09 21:26:03
您将在Autofac上注册两次控制器。
// This registers the all of the controllers in the application
builder.RegisterControllers(typeof(MvcApplication).Assembly);
// And so does this...
builder.RegisterModule(new MvcModule());MvcModule含量
public class MvcModule
: Module
{
protected override void Load(ContainerBuilder builder)
{
var currentAssembly = typeof(MvcModule).Assembly;
builder.RegisterAssemblyTypes(currentAssembly)
.Where(t => typeof(IController).IsAssignableFrom(t))
.AsImplementedInterfaces()
.AsSelf()
.InstancePerDependency();
}
}更新
来自这里
这个错误说明了一切--注册中的某些内容有一个依赖项,它注册为InstancePerRequest,并且它在web请求之外被解决。
我不确定将DBContext注册为InstancePerRequest是否是一个好主意。在创建任何请求上下文之前,MvcSiteMapProvider都会加载,所以如果您使用访问数据库的动态节点提供程序或自定义ISiteMapNodeProvider实现,它将无法工作。更好的选择是使用不依赖于InstancePerDependency的HttpContext。
每个依赖项实例
在其他容器中也称为“临时”或“工厂”。使用每个依赖范围,将从每个服务请求返回唯一的实例。
https://stackoverflow.com/questions/32469824
复制相似问题