Thomas
Thomas

Reputation: 34188

DI implementation with Constructor Injection using unity

i am new in DI pattern...now just learning.i got a code for Constructor Injection using unity. here is the code.

public class CustomerService
{
  public CustomerService(LoggingService myServiceInstance)
  { 
    // work with the dependent instance
    myServiceInstance.WriteToLog("SomeValue");
  }
} 

IUnityContainer uContainer = new UnityContainer();
CustomerService myInstance = uContainer.Resolve<CustomerService>();

here we can see CustomerService ctor looking for LoggingService instance but here when we create instance of CustomerService through resolve then we are not passing the instance of LoggingService. so tell me how could will work. any one explain it with small complete sample code. thanks

Upvotes: 0

Views: 1372

Answers (1)

Pete
Pete

Reputation: 6723

The code would look something like this:

public interface ILoggingService
{
    void WriteToLog(string logMsg);
}

public class LoggingService : ILoggingService
{
    public void WriteToLog(string logMsg)
    {
        ... WriteToLog implementation ...
    }
}

public interface ICustomerService
{
    ... Methods and properties here ...
}

public class CustomerService : ICustomerService
{

    // injected property
    public ISomeProperty SomeProperty { get; set; }

    public CustomerService(ILoggingService myServiceInstance)
    { 
        // work with the dependent instance
        myServiceInstance.WriteToLog("SomeValue");
    }
} 

...
...

// Bootstrap the container. This is typically part of your application startup.
IUnityContainer container = new UnityContainer();
container.RegisterType<ILoggingService, LoggingService>();

// Register ICustomerService along with injected property
container.RegisterType<ICustomerService, Customerservice>(
                            new InjectionProperty("SomeProperty", 
                                new ResolvedParameter<ISomeInterface>()));
...
...

ICustomerService myInstance = container.Resolve<ICustomerService>();

So when you resolve your ICustomerService interface, unity will return a new instance of CustomerService. When it instantiates the CustomerService object, it will see that it needs an ILoggingService implementation and will determine that LoggingService is the class it wants to instantiate.

There's more to it, but that's the basics.

Update - Added parameter injection

Upvotes: 2

Related Questions