简体   繁体   中英

.net 6 DI for base class

In .net 6 appeared new feature is DI by type anonymous delegate: 在此处输入图像描述

Questing: I have many clases inherited from based class with constructor.

now I have to write such long initializations在此处输入图像描述

Isn't there a way to get rid of this writing?, for example, like this (psevdocode)

在此处输入图像描述

This how parameter binding in minimal APIs (introduced in .NET 6) works and this is handled by the framework (ASP.NET Core). But it is not completely new idea and it is not bound to the anonymous labmdas - injection in controllers actions via FromServicesAttribute is present from the first ASP.NET Core (see applies to section) version.

As for tackling the parameter injection into the base class issue - one way around would be just creating class holding those parameters, register it in DI and injecting it. Something like this:

public class BaseClassParameters
{ 
    public BaseClassParameters (A a, B b, ...)  {A = a; ...}
    public A A { get; }
    ...
}

public class BaseClass
{
    public BaseClass(BaseClassParameters p) { // copy from p}
}


public class ChildClass : BaseClass
{
    public ChildClass(BaseClassParameters p): base(p) // can create ChildClassParameters : BaseClassParameters  if needed or just add deps on this level
    {
    }
}


services.AddTransient<BaseClassParameters>(); // or use needed lifetime for class hierarchy here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM