代码看起来像这样:
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>();
因此,当您解析 ICustomerService 接口时,unity 将返回一个新的 CustomerService 实例。当它实例化 CustomerService 对象时,它将看到它需要一个 ILoggingService 实现,并将确定 LoggingService 是它要实例化的类。
还有更多,但这是基础。
更新- 添加参数注入