基类中的属性注入

时间:2018-05-26 10:06:31

标签: c# asp.net-core dependency-injection castle-windsor aspnetboilerplate

在ASP.NET Boilerplate模板中,AppServiceBase有两个属性:TenantManagerUserManager

如果我需要使用这些属性,我应该执行以下操作:

public abstract class BaseClass
{
    public TenantManager TenantManager { get; set; }
    public UserManager UserManager { get; set; }

    ctor(TenantManager service1, UserManager service2)
    {
        TenantManager = service1;
        UserManager = service2;
    }
}

所以我在派生类ctor中请求这两个并将它们传递给基类:

public class DerivedClass : BaseClass
{
    ctor(TenantManager service1, UserManager service2)
        : base(service1, service2)
    {
    }

    public void SomeMethod()
    {
        // Use base class properties
        TenantManager.Something();
        UserManager.Something();
    }
}

在ASP.NET Core DI中,我可以执行以下操作:

public abstract class BaseClass
{
    public TenantManager Service1 => HttpContext.RequestServices.GetService<TenantManager>();
    public UserManager Service2 => HttpContext.RequestServices.GetService<UserManager>();

    ctor()
    {
    }
}

派生类不必在ctor中请求它们并将它们传递给基类:

public class DerivedClass : BaseClass
{
    ctor(ISpecificService service)
    {
        // I can have other types injected,
        // but TenantManager and UserManager will still be available to use
    }

    public SomeMethod()
    {
        // Use base class properties
        Service1.Something();
        Service2.Something();
    }
}

那么,我怎样才能在ABP中实现上述目标?

我试过了:

public abstract class BaseClass
{
    public TenantManager TenantManager { get; set; }
    public UserManager UserManager { get; set; }

    ctor()
    {
        var t = IocManager.Instance.CreateScope();
        TenantManager = t.Resolve<TenantManager>(); 
        UserManager = t.Resolve<UserManager>();
    }
}

但是,如果我在派生类中访问这些属性,则它们已被释放。但根据文档,它应该存在,直到我的课程被释放。

1 个答案:

答案 0 :(得分:1)

如果您未在构造函数中使用范围,请不要创建范围。

Property injection pattern无法在构造函数中解析。

public abstract class BaseClass
{
    public TenantManager TenantManager { get; set; }
    public UserManager UserManager { get; set; }

    ctor()
    {
    }
}