简体   繁体   English

Unity DI-使用构造函数解析接口

[英]Unity DI - resolve interface using constructor

I have this code: 我有以下代码:

var container = new UnityContainer();
container.RegisterType<Service>(new ContainerControlledLifetimeManager());

class Class1{
  public Class1(Service service){
    service.Add("123");
  }
}

class Class2{
  public Class2(Service service){
    var data = service.Get(); // return 123
  }
}

I have one service which is singleton. 我有一项服务是单身人士。 But I would like to inject using constructor: 但是我想使用构造函数注入:

var container = new UnityContainer();
    container.RegisterType<IService, Service>(new ContainerControlledLifetimeManager());

class Class1{
   public Class1(IService service){
     service.Add("123");
   }
 }

 class Class2{
   public Class2(IService service){
     var data = service.Get(); // return null
   }
 }

Now Service isnt singleton. 现在服务不是单例。 Why? 为什么? How to change my code to make it work properly? 如何更改我的代码以使其正常工作? Thanks 谢谢

You are checking smthg wrong since this code should work as expected. 您正在检查smthg错误,因为此代码应可以正常工作。 For example, we can have 例如,我们可以

class Class1
{
    public Class1(IService service)
    {
        service.Add("123");
    }
}

class Class2
{
    public Class2(IService service)
    {
        var data = service.Get(); // return NOT null
        Console.WriteLine(data);
    }
}

public interface IService 
{ 
    string Get();
    void Add(string item);
}

public class Service : IService 
{ 
    private string value;
    public string Get()=>value;
    public void Add(string item)=>value = item;
}

And we can test it with: 我们可以使用以下方法进行测试:

var container = new UnityContainer();
container.RegisterType<IService, Service>(new ContainerControlledLifetimeManager());

var cl1 = container.Resolve<Class1>(); // here in ctor we are setting value to 123
var cl2 = container.Resolve<Class2>(); // here we will print it to console

Output: 输出:

123

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

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