DI (Dependency Injection) 原理

摘要:DI原理

可以參考 阿尼大的 製造假象的類別

感謝阿尼大的指導 Orz

Service / Dao :


public class DemoService : IDemoService
{
	public IDemoDao DemoDao { get; set;}
}

public class DemoDao : IDemoDao
{
}

 

通常Service是在UI端所呼叫,透過DI的方式可以寫成: ( for Enterprise Library 5 )


private IDemoService _demoService;
private IDemoService DemoService {
	get {
		if (_demoService == null)
		{
			UnityContainer container = new UnityContainer();
            UnityConfigurationSection section = (UnityConfigurationSection)Config.GetSection("unity");
            section.Configure(container, "ContainerName");
			_demoService = container.Resolve<IDemoService>(); 
		}
		return _demoService;
	}
} 

 

要透過DI的方式免不了要設定config (XML)


<!--註冊 Service 區段-->
<register type="IDemoService" mapTo="DemoService">
	<property name="DemoDao">
		<dependency type="IDemoDao" />
	</property>
</register>

<!--註冊 Dao 區段-->
<register type="IDemoDao" mapTo="DemoDao" />

而DI的原理為: ( for Service)


string ServiceName = 透過config取得DemoService
object Service = Activator.CreateInstance(Type.GetType(ServiceName));

string DaoName = 透過config取得DemoDao
object Dao = Activator.CreateInstance(Type.GetType(DaoName));

string PropertyDaoName = 透過config取得DemoDao
Service.GetType().GetProperty(PropertyDaoName).SetValue(Service, Dao, null);

return Service;