我正在尝试创建一个可以注入到我的类中的 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
然后在网络请求之后处理它。现在我的问题是第二个 Web 请求似乎不再调用构造函数,因此只是重用以前创建的对象。这导致DatabaseContext
已经被处理掉了。
我以为LifestylePerWebRequest
意味着UserService
会根据每个请求重新创建。谁能帮助我理解这一点?