InstancePerRequest的MvcSiteMapProvider和Autofac问题

时间:2015-09-09 02:03:17

标签: c# entity-framework dependency-injection autofac mvcsitemapprovider

我已经安装了nutget包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的新手,所以我不太了解MvcSiteMapProvider Autofac的nuget包中的很多代码。虽然我更多地了解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;
}

0 个答案:

没有答案