[英]MvcSiteMapProvider and Autofac issue with InstancePerRequest
我已經安裝了堅果包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;
}
您正在使用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
實現,則它將無法正常工作。 更好的選擇是使用不依賴於HttpContext
InstancePerDependency
。
在其他容器中也稱為“瞬態”或“工廠”。 使用每個依賴關系范圍,每個服務請求都將返回一個唯一實例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.