1

我有3个项目:

Core(包含存储库、服务等的域模型和接口)
Repository(存储库的具体实现)
Web(MVC 4 项目)。

在 ObjectFactory.Initialize 我有这样的东西:

For<IFooRepository>().Use<FooRepository>();
For<IBooRepository>().Use<BooRepository>();
...

假设我有 50 个存储库,这是否意味着我必须编写 50 行代码(每个具体实现一个)?能StructureMap以某种方式找出FooRepository实现接口并在请求接口IFooRepositor时实例化该类吗?IFooRepository

任何帮助将不胜感激!

4

1 回答 1

3

StructureMap 确实允许您通过扫描程序集并应用约定将接口连接到类型来以编程方式执行此操作。这是一个例子:

public class RepositoryRegistry : StructureMap.Configuration.DSL.Registry
{
    public RepositoryRegistry()
    {
        Scan(s =>
        {
            s.AssemblyContainingType<ApplicationRepository>();
            s.Convention<TypeNamingConvention>();
        });
    }
}

和:

public class TypeNamingConvention : IRegistrationConvention
{
    public void Process(Type type, Registry registry)
    {
        Type interfaceType = type.GetInterfaces()
            .ToList()
            .Where(t => t.Name.ToLowerInvariant().Contains("i" + type.Name.ToLowerInvariant()))
            .FirstOrDefault();

        if (interfaceType != null)
        {
            registry.AddType(interfaceType, type);
        }
    }
}   

并且您在初始化时调用注册表,如下所示:

ObjectFactory.Initialize(x => x.Scan(s =>
{
 s.TheCallingAssembly();
 s.LookForRegistries();
}));

This convention just assumes the standard that your type matches the interface + "I". Hopefully that gives you enough to go on.

于 2012-08-21T14:59:28.037 回答