c# – CastleWindsor LifeStyle.PerWebRequest的行为类似于singl
我正在尝试创建一个UserService,我可以在我的类中注入,这将保持用户当前登录到我的系统.
我使用CastleWindsor作为我的容器. 现在我的问题是我正在尝试使我的UserService是一次性的,以便在销毁对象时也会处理在创建时获取用户的数据库连接. 我在Global.asax.cs中添加了以下设置: private static void BootstrapContainer() { _container = new WindsorContainer().Install(FromAssembly.This()); var controllerFactory = new WindsorControllerFactory(_container.Kernel); ControllerBuilder.Current.SetControllerFactory(controllerFactory); GlobalConfiguration.Configuration.DependencyResolver = new WindsorDependencyResolver(_container.Kernel); _container.Register(Component.For<IUserService>() .LifestylePerWebRequest() .ImplementedBy<UserService>()); _container.Register(Component.For<IPrincipal>() .LifeStyle.PerWebRequest .UsingFactoryMethod(() => HttpContext.Current.User)); } 在我的Application_Start中调用了哪个. 我的UserService代码如下: public interface IUserService { OrganisationBruger User { get; } int UserId { get; } } public class UserService : IUserService,IDisposable { private readonly IPrincipal _principal; private OrganisationBruger _user; private readonly DatabaseDataContext _db; public UserService(IPrincipal principal,IDatabaseDataContextFactory dataContextFactory) { _principal = principal; _db = dataContextFactory.GetDataContext(); } public OrganisationBruger User => _user ?? (_user = GetUser()); public int UserId => Convert.ToInt32(_principal.Identity.Name); private OrganisationBruger GetUser() { return _db.OrganisationBrugers.Single(u => u.ID == UserId); } public void Dispose() { _db.Dispose(); } } 当我调试我的代码时,我可以在第一个请求中看到我正确启动它创建类UserService.cs然后在webrequest之后处理它.现在我的问题是第二个Web请求似乎不再调用构造函数,因此只是重用以前创建的对象.这导致DatabaseContext已被处理掉. 我认为LifestylePerWebRequest意味着每次请求都会重新创建UserService.任何人都可以帮我理解这个吗? 解决方法
首先,我忽略了文档中的“模块注册”部分.您需要将以下内容添加到web.config:
<httpModules> <add name="PerRequestLifestyle" type="Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule,Castle.Windsor"/> </httpModules> 其次,我并不是百分之百确定依赖解析器是如何工作的.问题是使用我的UserService作为依赖项的模块之一将其生命周期设置为Singleton,当您在向容器注册模块时未指定生命周期时,这是默认行为. 我通过确保使用我的UserService作为依赖项的每个模块也注册了LifestylePerWebRequest()或LifestyleTransient()的生命周期来解决问题. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |