Search code examples
c#asp.net-coredependency-injectioncastle-windsoraspnetboilerplate

Property injection in base class


In the ASP.NET Boilerplate template, there is an AppServiceBase that has two properties: TenantManager and UserManager.

If I need to use these properties, I should do something like:

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

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

So I request these two in my derived class ctor and pass them to base class:

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

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

In ASP.NET Core DI, I could do something like:

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

    ctor()
    {
    }
}

And derived classes don't have to request them in ctor and pass them to base class:

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();
    }
}

So, how can I achieve something like above in ABP?

I tried:

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>();
    }
}

However, if I access these properties in derived class, they are already disposed. But according to the documentation, it should live till my class is released.


Solution

  • Don't create scope if you're not using the scope in the constructor.

    Property injection pattern works without resolving in the constructor.

    public abstract class BaseClass
    {
        public TenantManager TenantManager { get; set; }
        public UserManager UserManager { get; set; }
    
        ctor()
        {
        }
    }