简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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