Unity Application Block的使用中有两种手动向Unity container注册mappings 的类,即RegisterType和RegisterInstance,他们的不同是:
1、RegisterType向Unity container中注册类型(registers a type ),可以是接口或是一个基类,在使用Resolve 方法获得对象时,dependency injection特性将其作用;默认情况下lifetime是短周期,每次使用 Resolve 方法都获得一个新对象;如果想使用单件的,可以这样:
container.RegisterType<CustomerService>(new ContainerControlledLifetimeManager());
2、RegisterInstance则是注册实例 (instance),默认情况下每次使用 Resolve 方法都获得同一个对象,即单件模式;
如果想让实例的dependency injection特性起作用,要使用BuildUp 方法,即
public class Log4X : MarshalByRefObject
{
[Microsoft.Practices.Unity.Dependency]
public MyWriter writer { get; set; }
public Log4X()
{
//this.writer = writer;
}
public void Writer(string message)
{
writer.Writer(message);
}
}
public class MyWriter
{
public void Writer(string message)
{
Console.WriteLine();
Console.WriteLine("===========In MyWriter===============");
Console.WriteLine("message:{0}", message);
}
}
调用:
Log4X logger = new Log4X();
container.BuildUp<Log4X>(logger);
logger.Writer("你好");
还可以进行一次进行多个注册操作:
EmailService myEmailService = new EmailService();
IUnityContainer myContainer = new UnityContainer()
.RegisterType<IMyService, DataService>()
.RegisterType<IMyUtilities, DataConversions>()
.RegisterInstance<IMyService>(myEmailService);