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
The code would look something like this:
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