我们正在评估国际奥委会为C项目提供的集装箱,包括Unity和Castle。温莎很突出。我喜欢Unity(Ninject和StructureMap也这样做)的一点是,对于那些显而易见如何构造它们的类型,不必在IOC容器中注册。
在城堡里有办法吗?温莎?我对城堡公平吗?温莎说这不公平吗?是否有设计原因故意不这样做,或者这是一个疏忽,或者只是不被视为重要或有用?
我知道
container.Register(AllTypes...
在温莎,但那不是完全一样的事情。它不是完全自动的,而且非常广泛。
为了说明这一点,这里有两个修女测试通过Unity和Castle.Windsor做同样的事情。城堡。温莎一号失败了。:
namespace SimpleIocDemo
{
using NUnit.Framework;
using Castle.Windsor;
using Microsoft.Practices.Unity;
public interface ISomeService
{
string DoSomething();
}
public class ServiceImplementation : ISomeService
{
public string DoSomething()
{
return "Hello";
}
}
public class RootObject
{
public ISomeService SomeService { get; private set; }
public RootObject(ISomeService service)
{
SomeService = service;
}
}
[TestFixture]
public class IocTests
{
[Test]
public void UnityResolveTest()
{
UnityContainer container = new UnityContainer();
container.RegisterType<ISomeService, ServiceImplementation>();
// Root object needs no registration in Unity
RootObject rootObject = container.Resolve<RootObject>();
Assert.AreEqual("Hello", rootObject.SomeService.DoSomething());
}
[Test]
public void WindsorResolveTest()
{
WindsorContainer container = new WindsorContainer();
container.AddComponent<ISomeService, ServiceImplementation>();
// fails with exception "Castle.MicroKernel.ComponentNotFoundException:
// No component for supporting the service SimpleIocDemo.RootObject was found"
// I could add
// container.AddComponent<RootObject>();
// but that approach does not scale
RootObject rootObject = container.Resolve<RootObject>();
Assert.AreEqual("Hello", rootObject.SomeService.DoSomething());
}
}
}