我從來沒有使用IoC容器與WebForms,所以得到這個作爲一些高層次的解決方案,應該可能進一步改進。
你可以嘗試創造一些國際奧委會提供的單身:
public class IoCProvider
{
private static IoCProvider _instance = new IoCProvider();
private IWindsorContainer _container;
public IWindsorContainer
{
get
{
return _container;
}
}
public static IoCProvider GetInstance()
{
return _instance;
}
private IoCProvider()
{
_container = new WindsorContainer(new XmlInterpreter(new ConfigResource("castle")));
}
}
你web.config
必須包含的部段(該配置是基於你的previous post):
<configuration>
<configSections>
<section name="castle" type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor" />
</configSections>
<castle>
<components>
<component id="DalLayer"
service="MyDal.IDalLayer, MyDal"
type="MyDal.MyDalLayer, MyDal"
lifestyle="PerWebRequest">
<!--
Here we define that lifestyle of DalLayer is PerWebRequest so each
time the container resolves IDalLayer interface in the same Web request
processing, it returns same instance of DalLayer class
-->
<parameters>
<connectionString>...</connectionString>
</parameters>
</component>
<component id="BusinessLayer"
service="MyBll.IBusinessLayer, MyBll"
type="MyBll.BusinessLayer, MyBll" />
<!--
Just example where BusinessLayer receives IDalLayer as
constructor's parameter.
-->
</components>
</castle>
<system.Web>
...
</system.Web>
</configuration>
這些接口的實現並且類可以看起來像:
public IDalLayer
{
IRepository<T> GetRepository<T>(); // Simplified solution with generic repository
Commint(); // Unit of work
}
// DalLayer holds Object context. Bacause of PerWebRequest lifestyle you can
// resolve this class several time during request processing and you will still
// get same instance = single ObjectContext.
public class DalLayer : IDalLayer, IDisposable
{
private ObjectContext _context; // use context when creating repositories
public DalLayer(string connectionString) { ... }
...
}
public interface IBusinessLayer
{
// Each service implementation will receive necessary
// repositories from constructor.
// BusinessLayer will pass them when creating service
// instance
// Some business service exposing methods for UI layer
ISomeService SomeService { get; }
}
public class BusinessLayer : IBusinessLayer
{
private IDalLayer _dalLayer;
public BusinessLayer(IDalLayer dalLayer) { ... }
...
}
比你能定義基類爲您的網頁,並暴露業務層(你可以做同樣的與任何其他類可以解決):
public abstract class MyBaseForm : Page
{
private IBusinessLayer _businessLayer = null;
protected IBusinessLayer BusinessLayer
{
get
{
if (_businessLayer == null)
{
_businessLayer = IoCProvider.GetInstance().Container.Resolve<IBusinessLayer>();
}
return _businessLayer;
}
...
}
複雜的解決方案對子級涉及使用自定義PageHandlerFactory
直接解決網頁和注入依賴關係。如果你想使用這樣的解決方案,請檢查Spring.NET框架(帶IoC容器的另一個API)。
謝謝拉迪斯拉夫。如果可以的話,我會+10! – Kamyar 2011-01-07 17:46:27