微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – CastleWindsor LifeStyle.PerWebRequest的行为类似于singleton

我正在尝试创建一个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()的生命周期来解决问题.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐