Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在Unity依赖项注入框架中,是否存在与使用注入构造函数运行构建等效的方法?_C#_Dependency Injection_Unity Container_Constructor Injection - Fatal编程技术网

C# 在Unity依赖项注入框架中,是否存在与使用注入构造函数运行构建等效的方法?

C# 在Unity依赖项注入框架中,是否存在与使用注入构造函数运行构建等效的方法?,c#,dependency-injection,unity-container,constructor-injection,C#,Dependency Injection,Unity Container,Constructor Injection,在DI框架中,我一直想要的一件事是能够将注入构造函数与只与框架交互以使用服务的对象一起使用。例如: public class ServiceClass : IServiceInterface { public string Name { get; set; } } public class ConsumerClass // explicitly implements no interfaces { private readonly IServiceInterface servi

在DI框架中,我一直想要的一件事是能够将注入构造函数与只与框架交互以使用服务的对象一起使用。例如:

public class ServiceClass : IServiceInterface
{
    public string Name { get; set; }
}

public class ConsumerClass // explicitly implements no interfaces
{
    private readonly IServiceInterface service;
    public IServiceInterface Service { get { return service; } }

    [InjectionConstructor]
    public ConsumerClass(IServiceInterface service)
    {
        this.service = service;
    }
}

static void Main()
{
    IUnityContainer container;
    // blah blah DI setup stuff
    container.RegisterType<IServiceInterface, ServiceClass>();

    // Key point here!
    container.Instantiate<ConsumerClass>();
    // Alternatively:
    container.Instantiate(typeof(ConsumerClass));
}
公共类服务类:IServiceInterface
{
公共字符串名称{get;set;}
}
公共类ConsumerClass//未显式实现任何接口
{
专用只读服务器接口服务;
公共IServiceInterface服务{get{return Service;}}
[注入构造函数]
公共消费类(IServiceInterface服务)
{
服务=服务;
}
}
静态void Main()
{
i单元容器;
//诸如此类的设置
container.RegisterType();
//关键点在这里!
container.Instantiate();
//或者:
实例化(typeof(ConsumerClass));
}
IUnityContainer的build()方法可以做到这一点,但它需要传入一个实例,如果我想使用注入构造函数,我不能这样做

此外,我可以使用:

    container.RegisterType(typeof(ConsumerClass), 
        new InjectionConstructor(container.Resolve<IServiceClass>()));
container.RegisterType(typeof(ConsumerClass)),
新的注入构造函数(container.Resolve());
然而,这需要编写大量代码——特别是对于构造函数中可能有多个参数的类而言——并且似乎首先删除了容器的实用程序

还有:

    container.RegisterType<ConsumerClass, ConsumerClass>();  
container.RegisterType();
然而,对于这一个,我实际上不想注册类型——我只想创建它,并通过InjectionConstructor填充其依赖项


总之:我想使用注入构造函数,我想让Unity为我做注册服务的映射,如果可能的话,我想让我的消费者远离容器。有没有一种方法我错过了?

正如您所发现的那样,
.build
方法只对现有实例有效,要使用Unity创建新实例,您需要使用
.Resolve
方法,这些方法将在需要时创建注入任何依赖项的实例

对于您的示例,使用
var consumer=container.Resolve()
,所有依赖项都将被注入。您不需要注册
ConsumerClass
,因为它是Unity能够隐式处理的具体类型