![](/img/trans.png)
[英]How to run the supplied IOC (Inversion Of Control) demo from Castle Windsor docs?
[英]How do i implement Inversion of control using Castle Windsor
我在使用windsor实施IOC时遇到一些问题。 我有几种不同的数据访问类实现,并且我想使用windsor来指定使用业务对象时要使用的数据访问类。 见下面的代码
public interface IPersistable
{
bool Save();
bool Delete();
}
public class Address
{
public Address()
{
}
public Address(IPersistable Factory)
{
this.DataAccess = Factory;
}
private IPersistable _DataAccess;
public IPersistable DataAccess
{
get { return _DataAccess; }
set { _DataAccess = value; }
}
}
public class AddressFactoryUsingSQL : IPersistable
{
public bool Save()
{
throw new NotImplementedException();
}
public bool Delete()
{
throw new NotImplementedException();
}
}
public class AddressFactoryUsingWebService : IPersistable
{
public bool Save()
{
throw new NotImplementedException();
}
public bool Delete()
{
throw new NotImplementedException();
}
}
public class AddressFactoryUsingRepository : IPersistable
{
public bool Save()
{
throw new NotImplementedException();
}
public bool Delete()
{
throw new NotImplementedException();
}
}
当使用以下类消耗类时添加: Address addr = new Address(new AddressFactoryUsingSQL);
我希望能够使用Windsor,因此我可以编写类似于以下内容的内容:
IWindsorContainer _Container= new WindsorContainer();
_Container.Register(Castle.MicroKernel.Registration.Component.For<IPersistable>()); //this would retrieve the IPersistable class i want to use for the Address business object
IPersistable addrF = _Container.Resolve<IPersistable>();
Address addr = new Address(addrF);
我该如何实现? 我收到错误消息,“类型IPersistable是抽象的。因此,无法将其实例化为IPersistable服务的实现”
我希望能够更改数据访问方法而不必更改我的所有代码。 另外,我该如何使用web.config?
铝
问题是您忘记提及实现IPersistable的以下具体类型,下面的代码应该可以工作:
IWindsorContainer container = new WindsorContainer();
container.Register(
Component.For<IPersistable>()
.ImplementedBy<AddressFactoryUsingSQL>());
您可以通过以下方式使用它:
var persistable = container.Resolve<IPersistable>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.