c# - 仅从指定的命名空间解决依赖关系

标签 c# unity-container conventions

我可以用这条语句自动注册所有实现接口(interface)的类型

IUnityContainer container = new UnityContainer();

container.RegisterTypes(
    AllClasses.FromAssembliesInBasePath(),
    WithMappings.FromMatchingInterface,
    WithName.Default,
    WithLifetime.Transient);
ICustomer result = container.Resolve<ICustomer>();

如何为接口(interface)和实现指定命名空间?

即:只有 Framework.RepositoryInterfaces 中的接口(interface)应该由 Framework.RepositoryImplementations 中的类型解析。

最佳答案

您可以使用 RegistrationConvention :

public class NamespaceRegistrationConvention : RegistrationConvention
{
    private readonly IEnumerable<Type> _typesToResolve;
    private readonly string _namespacePrefixForInterfaces;
    private readonly string _namespacePrefixForImplementations;

    public NamespaceRegistrationConvention(IEnumerable<Type> typesToResolve, string namespacePrefixForInterfaces, string namespacePrefixForImplementations)
    {
        _typesToResolve = typesToResolve;
        _namespacePrefixForInterfaces = namespacePrefixForInterfaces;
        _namespacePrefixForImplementations = namespacePrefixForImplementations;
    }

    public override IEnumerable<Type> GetTypes()
    {
        // Added the abstract as well. You can filter only interfaces if you wish.
        return _typesToResolve.Where(t =>
            ((t.IsInterface || t.IsAbstract) && t.Namespace.StartsWith(_namespacePrefixForInterfaces)) ||
            (!t.IsInterface && !t.IsAbstract && t.Namespace.StartsWith(_namespacePrefixForImplementations)));
    }

    public override Func<Type, IEnumerable<Type>> GetFromTypes()
    {
        return WithMappings.FromMatchingInterface;
    }

    public override Func<Type, string> GetName()
    {
        return WithName.Default;
    }

    public override Func<Type, LifetimeManager> GetLifetimeManager()
    {
        return WithLifetime.Transient;
    }

    public override Func<Type, IEnumerable<InjectionMember>> GetInjectionMembers()
    {
        return null;
    }
}

并通过以下方式使用它:

container.RegisterTypes(new NamespaceRegistrationConvention(AllClasses.FromAssembliesInBasePath(), "Framework.RepositoryInterfaces", "Framework.RepositoryImplementations");
ICustomer result = container.Resolve<ICustomer>();

关于c# - 仅从指定的命名空间解决依赖关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38062829/

相关文章:

c# - 当前上下文中不存在 HttpUtility

c# - RichTextBox 选择部分文本

c# - 在下游生成新的 Windows 窗体时如何使用 DI?

C 中的相互依赖定义

c# - C# 上的文字效果

c# - 使用正则表达式解析文本文件

c# - aspnet core web.config 未加载

c# - 在 SpecFlow 步骤文件中使用依赖注入(inject)

c# - 我可以在 c# .NET 中强制使用 'this' 关键字吗?

关于传递对象的 C++ 约定(指针与引用)