如何使用AutoFac使用关联类型的对象解析依赖关系?

时间:2017-11-17 23:46:04

标签: dependency-injection autofac dependency-management

我很难弄清楚如何使用AutoFac在容器中的对象之间创建1:1映射。我收到解决方案错误,文档太简洁,没有足够的示例。

这是我想用来解决依赖关系的规则: IHouse对象只能使用特定具体类型的IDoor参数构造,在IHouse和IDoor类型之间创建1:1映射。

例如,使用下面的代码,如果我使用MonkeyDoor解析容器,它应该给我一个完全构造的MonkeyHouse和一个MonkeyHouse对象。

[TestClass]
public class HousingDeveloperTest
{
    [TestMethod]
    public void TestMethod1()
    {
        // Load them from an assembly or disc. We are interested in IHouse and IDoor types
        var builder = new ContainerBuilder();

        // Get all the houses
        var assembly = Assembly.GetExecutingAssembly();
        builder.RegisterAssemblyTypes(assembly)
            .Where(t => t.Name.EndsWith(nameof(House))).AsImplementedInterfaces();

        // get all the doors
        builder.RegisterAssemblyTypes(assembly)
            .Where(t => t.Name.EndsWith(nameof(Door))).AsImplementedInterfaces(); 

        var container = builder.Build();

        using (var scope = container.BeginLifetimeScope())
        {

            var house = container.Resolve<IDoor>(new TypedParameter(typeof(MonkeyDoor), new MonkeyDoor()));
        }
    }
}


public interface IDoor
{
    void Open();
}

public abstract class Door : IDoor
{
    public void Open()
    {
        Trace.WriteLine($"Opening {GetType().ToString()}.");
    }
}

// Only works with Victorian homes
public class VictorianDoor : Door
{
}

// Only works with Craftsman homes
public class CraftsmanDoor : Door
{
}

// Only works with monkey homes
public class MonkeyDoor : Door
{
}

public interface IHouse
{
    void OpenHouse();
}

public abstract class House : IHouse
{
    public IDoor Door;

    protected House(IDoor door)
    {
        Door = door;
        Trace.WriteLine($"Building this {this.GetType()} with {door.GetType()} door.");
    }

    public void OpenHouse()
    {
        Trace.WriteLine($"We're having an open house on this wonderful {this.GetType().ToString()}.");
        Door.Open();
    }
}

// Doors must match the homes. (i.e. No monkey doors on a Victorian or Craftsman home.)
public class VictorianHouse : House
{
    public VictorianHouse(VictorianDoor door) : base(door)
    {
    }
}

public class CraftsmanHouse : House
{
    public CraftsmanHouse(CraftsmanDoor door) : base(door)
    {
    }
}

public class MonkeyHouse : House
{
    public MonkeyHouse(MonkeyDoor door) : base(door)
    {
    }
}

0 个答案:

没有答案