我为我们的项目设置了Unity for dependency injection.项目本身是一个使用MVC和Web API的ASP.NET应用程序.
对于数据库上下文,我正在使用PerRequestLifetimeManager.这样做是为了使业务逻辑的不同位使用相同的上下文(因而是相同的事务).
为了能够使用PerRequestLifetimeManager,我添加了针对ASP.NET MVC的nuget包Unity引导程序和ASP.NET Web API的Unity引导程序的引用.
要在Web API中使用此生命周期管理器,已在启动代码中添加以下行:
Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility.RegisterModule(typeof(UnityPerRequestHttpModule));
Run Code Online (Sandbox Code Playgroud)
Unity容器是为MVC和Web API设置的:
var container = BuildUnityContainer();
GlobalConfiguration.Configuration.DependencyResolver = new Microsoft.Practices.Unity.WebApi.UnityDependencyResolver(container);
System.Web.Mvc.DependencyResolver.SetResolver(new Microsoft.Practices.Unity.Mvc.UnityDependencyResolver(container));
Run Code Online (Sandbox Code Playgroud)
在构建Unity容器时,数据库上下文设置为按请求以下列方式解析:
container.RegisterType<IDataContext>(new PerRequestLifetimeManager(),
new InjectionFactory(c =>
{
// Some code
return new DataContext(/* params */);
}
));
Run Code Online (Sandbox Code Playgroud)
但是,似乎这段代码并没有DataContext为每个请求提供新的代码.它在一个请求中给出了我在不同地方的相同上下文(这很好).但是,后续(web api)请求被赋予了相同的实例DataContext,我希望为每个新请求创建一个新的请求.我也希望在DataContext请求完成后(类实现IDisposable)正确处理.
这里发生了什么?我是否缺少一些配置才能使其正常工作?或者这不应该像我期望的那样工作?