2013-04-04 91 views
3

我们正在将一个现有的日志记录库封装到C#应用程序中的自己的日志记录服务中,以便在某些日志记录情况下使用预定义的方法将它包围。通用依赖注入与Unity

public class LoggingBlockLoggingService : ILoggingService 
{ 
    private LogWriter writer; 

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

我想,这样只有在对其进行实例化类的类型来修改这个实现(底层记录,日志写在这种情况下,将是一个单例)。因此,要么让这个实现(和接口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. 
} 

是否有注册我们的类型时,配置此一次团结方式?我想避免为每个想要登录的课程添加条目。理想情况下,如果有人想将日志记录添加到项目中的类中,他们只需将ILoggingService添加到正在工作的类的构造函数中,而不是将另一行添加到我们的Unity配置中以注册他们正在处理的每个类。

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

回答

8

是的,你可以使用:

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

+0

宾果,谢谢! 我曾尝试类似的东西与container.RegisterType 。删除尖括号并使用基本方法正是我所需要的。 – Dan 2013-04-04 15:24:03

0

在你的情况,如果有简单的直接仿制PARAM - 以--generic-param映射Unity可能实际上处理了这个问题,但我怀疑没有处理任何更高级的情况,因为某些时间点的某些事物必须提供类型之间的泛型参数映射(liek reordering Key-Value vs 。Value-Key等)。

如果Dave的答案还不够,我相当肯定你可以为Unity/ObjectBuilder编写一个插件,它将注册一个新的策略或一组策略,这些策略或策略将涵盖所有你想要的类型映射,包括自动组装扫描或实现泛型。

看到http://www.orbifold.net/default/unity-objectbuilder-part-ii/的系列文章和部分附近

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