Search code examples
c#unity-container

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


Solution

  • You are checking smthg wrong since this code should work as expected. 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