1 year ago

#231406

test-img

user1263981

How to use constructor dependency injection using unity in the test class

I am using Unity container to achieve the constructor DI in the console application. The dependency registration is done in the Main method of a program class.

All works fine but i am not able to achieve the constructor DI in the Test Class 'ClientSearchTest'. I have to create a new object in the test class using new operator to make it work.

Unity container should take care of creating a new object instead it being created manually using NEW operator.

Program

static void Main(string[] args)
{
    // Register the dependencies
    container = RegisterDependency(new UnityContainer());

    var program  = container.Resolve<ExportClientDetails>();
    program.Run();
}

//register the type-mapping with the unity container
private static IUnityContainer RegisterDependency(IUnityContainer container)
{
    container.RegisterType<IClientOperation, ClientOperation>();
    container.RegisterType<IClientSearch, ClientSearch>();

    return container;
}

class ExportClientDetails
{
     private readonly IClientSearch _clientSearch;

     //Constructor Injection
     public ExportClientDetails(IClientSearch clientSearch)
     {
            this._clientSearch = clientSearch;
     }

}

public class ClientSearch : IClientSearch
{
   private readonly IClientOperation _clientOperation;
 
    //constructor
    public ClientSearch(IClientOperation clientOperation)
    {
        _clientOperation = clientOperation;
    }
}

Test

[TestClass]
public class ClientSearchTest
{
    private IClientSearch _clientSearch;
    private IClientOperation _clientOperation;

    [TestInitialize]
    public void TestInitialize()
    {
        _clientOperation = new ClientOperation();
        _clientSearch = new ClientSearch(_clientOperation);
    }

}

c#

dependency-injection

inversion-of-control

unity-container

0 Answers

Your Answer

Accepted video resources