{
private MockRepository mocks;
public AutoMockingUnityContainer(MockRepository mocks)
{
this.mocks = mocks;
}
public AutoMockingUnityContainer WillReturnAStubFor<T>() where T : class
{
return (AutoMockingUnityContainer) this.RegisterType(typeof(T), null, null, new StubFactory(typeof(T), mocks,Lifetime.Singleton));
}
public AutoMockingUnityContainer WillCreateMockFor<T>() where T : class
{
return (AutoMockingUnityContainer) this.RegisterType(typeof(T), null, null, new MockFactory(typeof(T),mocks,Lifetime.Singleton));
}
public AutoMockingUnityContainer WillCreatePartialMockFor<T>(Lifetime lifetime) where T : class
{
return (AutoMockingUnityContainer) this.RegisterType(typeof(T), null, null, new PartialMockFactory(typeof(T), mocks, lifetime));
}
private abstract class AbstractFactory : ContainerControlledLifetimeManager
{
protected Type theType;
protected Lifetime lifetime;
protected AbstractFactory(Type theType, MockRepository mocks, Lifetime lifetime)
{
this.theType = theType;
this.lifetime = lifetime;
this.mocks = mocks;
}
protected MockRepository mocks;
protected abstract object GetTheObject(Type type);
public override object GetValue()
{
object value = base.GetValue();
if (lifetime==Lifetime.NewEveryTime || value == null)
{
value = GetTheObject(theType);
SetValue(value);
}
return value;
}
}
class MockFactory: AbstractFactory
{
public MockFactory(Type theType, MockRepository mocks, Lifetime lifetime)
: base(theType, mocks, lifetime)
{
}
protected override object GetTheObject(Type type)
{
return mocks.CreateMock(type);
}
}
class StubFactory: AbstractFactory
{
public StubFactory(Type theType, MockRepository mocks, Lifetime lifetime)
: base(theType, mocks, lifetime)
{
}
protected override object GetTheObject(Type type)
{
return mocks.Stub(type);
}
}
class PartialMockFactory: AbstractFactory
{
public PartialMockFactory(Type theType, MockRepository mocks,
Lifetime lifetime) : base(theType, mocks, lifetime)
{
}
protected override object GetTheObject(Type type)
{
return mocks.PartialMock(theType);
}
}
}
public enum Lifetime
{
Singleton,
NewEveryTime
}