WebForms과 함께 IoC 컨테이너를 사용 해 본 적이 없으므로이 기능을 일부 개선 된 수준으로 개선해야합니다.
당신 싱글 톤 등 일부 IOC의 공급자를 만드는 시도 할 수 있습니다 :
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
를 사용하여 포함 whould 및 의존성을 주입하십시오. 그러한 솔루션 체크 Spring.NET 프레임 워크 (IoC 컨테이너가있는 다른 API)를 사용하려는 경우.
Ladislav. 만약 내가 할 수 있다면, 나는 그것을 +10했습니다! – Kamyar