Test classes

interface IMock
{
    string Name { get; }
    
    int Value { get; }
}

class MockA : IMock
{
    //constructor injection
    public MockA(string name, int @value)
    {
        Name = name;
        Value = @value;
    }

    public string Name { get; private set; }

    public int Value { get; private set; }
}

class MockB : IMock
{
    //property injection
    [Dependency]
    public string Name { get; private set; }

    //property injection with key
    [Dependency(Name = "int_name")]
    public int Value { get; private set; }
}

Resolve type

void ResolveType()
{
    //create container
    IUnityContainer container = new UnityContainer();

    //register instances
    container.RegisterInstance("Name");
    container.RegisterInstance(1);

    //resolve type
    MockA result1 = container.Resolve<MockA>();
    //output: Type = MockA, Name = 'Name', Value = '1'

    //register with key
    container.RegisterType<IMock, MockA>("key");
    IMock result2 = container.Resolve<IMock>("key");
    //output: Type = MockA, Name = 'Name', Value = '1'

    container.RegisterInstance(77, "int_name");
    container.RegisterType<IMock, MockB>("key_B");
    IMock result3 = container.Resolve<IMock>("key_B");
    //output: Type = MockB, Name = 'Name', Value = '77'

    IMock result4 = container.Resolve<IMock>("non-existent");
    //exception is thrown
}

Last edited Mar 7, 2010 at 8:17 AM by kirill_polishchuk, version 2

Comments

No comments yet.