Unity依赖注入-在MVC 5 Web应用程序中按http请求生命周期管理问题

时间:2018-08-15 14:00:35

标签: c# asp.net-mvc dependency-injection asp.net-mvc-5 unity-container

我正在尝试为每个HTTP请求实现实例的生命周期(在Unity DI中)。但是当我尝试注册实例时,我一直收到错误消息:“ PerRequestLifetimeManager只能在HTTP请求的上下文中使用。此错误的可能原因是在非ASP.NET应用程序上使用生命周期管理器,或在与适当的同步上下文无关的线程中使用它。

我在UnityMvcActivator.cs中注册了UnityPerRequestHttpModule,如下所示

public static void Start() 
        {
            FilterProviders.Providers.Remove(FilterProviders.Providers.OfType<FilterAttributeFilterProvider>().First());
            FilterProviders.Providers.Add(new UnityFilterAttributeFilterProvider(UnityConfig.Container));

            DependencyResolver.SetResolver(new UnityDependencyResolver(UnityConfig.Container));

            // TODO: Uncomment if you want to use PerRequestLifetimeManager
            Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility.RegisterModule(typeof(UnityPerRequestHttpModule));
        }

这就是我的UnityConfig.cs的样子

public static void RegisterTypes(IUnityContainer container)
        {
            // TODO: Register your type's mappings here.
            container.RegisterInstance<OITTimeSheetDBContextFactory>(new OITTimeSheetDBContextFactory(), new PerRequestLifetimeManager());
            container.RegisterInstance<UserContext>(new UserContext(container.Resolve<OITTimeSheetDBContextFactory>()), new PerRequestLifetimeManager());
        }

1 个答案:

答案 0 :(得分:2)

使用RegisterType进行 Per Resolve 实例化

public static void RegisterTypes(IUnityContainer container)
{
    container.RegisterType<OITTimeSheetDBContextFactory>(new PerRequestLifetimeManager());
    container.RegisterType<UserContext>(new PerRequestLifetimeManager());
}

RegisterInstance将有效地定义一个单例,并将始终返回该对象的相同实例