简体   繁体   English

.net 6 DI 用于基座 class

[英].net 6 DI for base class

In .net 6 appeared new feature is DI by type anonymous delegate:在 .net 6 中出现的新功能是 DI by type anonymous delegate: 在此处输入图像描述

Questing: I have many clases inherited from based class with constructor.追问:我有很多继承自带有构造函数的基于 class 的类。

now I have to write such long initializations现在我必须写这么长的初始化在此处输入图像描述

Isn't there a way to get rid of this writing?, for example, like this (psevdocode)有没有办法摆脱这种写法?例如,像这样(psevdocode)

在此处输入图像描述

This how parameter binding in minimal APIs (introduced in .NET 6) works and this is handled by the framework (ASP.NET Core).这是最小 API中的参数绑定(在 .NET 6 中引入)的工作原理,这是由框架(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.但这不是全新的想法,也不受匿名 labmdas 的约束 - 从第一个 ASP.NET 核心(参见适用于部分)版本开始,通过FromServicesAttribute注入控制器动作。

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.至于解决基本 class 问题的参数注入问题 - 一种解决方法是创建 class 持有这些参数,在 DI 中注册并注入它。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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