繁体   English   中英

Unity的通用依赖注入

[英]Generic dependency injection with Unity

我们将现有的日志记录库包装在我们自己的C#应用​​程序中的日志记录服务中,以便使用预定义的方法为特定的日志记录情

public class LoggingBlockLoggingService : ILoggingService
{
    private LogWriter writer;

    public LoggingBlockLoggingService(LogWriter writer)
    {
        this.writer = writer;
    }
    ....//logging convenience methods, LogWarning(), etc...
}

我想修改这个实现,以便它接受实例化它的类的类型(底层记录器,在这种情况下,LogWriter将是一个单例)。 所以要么使这个实现(和接口ILoggingService)通用:

public class LoggingBlockLoggingService<T> : ILoggingService<T>
{
    ...
    private string typeName = typeof(T).FulName;
    ...

或者添加一个额外的构造函数参数:

public class LoggingBlockLoggingService : ILoggingService
{
    private LogWriter writer;
    private string typeName;

    public LoggingBlockLoggingService(LogWriter writer, Type type)
    {
        this.writer = writer;
        this.typeName = type.FullName;
    }
    ....//Include the typeName in the logs so we know the class that is logging.
}

在注册我们的类型时,有没有办法在Unity中配置一次 我想避免为每个想要记录的类添加一个条目。 理想情况下,如果有人想在我们的项目中向类中添加日志记录,他们只需将ILoggingService添加到他们正在使用的类的构造函数中,而不是在我们的unity配置中添加另一行来注册他们正在处理的每个类。 。

我们使用的是运行时/代码配置,而不是XML

是的,你可以使用:

container.RegisterType(typeof(IMyGenericInterface<>), typeof(MyConcreteGenericClass<>));

在你的情况下,当有简单的直接泛型参数 - 通用 - 参数映射时,Unity实际上可以处理它,但我怀疑是否有任何更高级的情况都没有处理,因为在某些时候某些东西必须提供映射类型之间的泛型参数(谎言重新排序键值与价值键等)。

如果Dave的答案还不够,我相当肯定你可以为Unity / ObjectBuilder写一个插件,它会注册一个新策略或一套策略,它们可以覆盖你想要的任何类型映射,包括自动装配扫描或物化仿制药。

请参阅http://www.orbifold.net/default/unity-objectbuilder-part-ii/上的系列文章以及附近的部分

Context.Strategies.AddNew< buildkeymappingstrategy >(UnityBuildStage.TypeMapping);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM