通用依赖注入与团结 [英] Generic dependency injection with Unity

查看:167
本文介绍了通用依赖注入与团结的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们都包裹在我们自己的日志服务现有的日志库,在C#应用程序与特定的日志记录的情况下预定义的方法将其包围。

We are wrapping an existing logging library in our own logging service in a C# application to surround it with predefined methods for certain logging situations.

public class LoggingBlockLoggingService : ILoggingService
{
    private LogWriter writer;

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

我想这样,它需要在实例化的类的类型来修改这个实现(底层记录,日志写在这种情况下,将是一个单例)。因此,要么让这个实现(和接口ILoggingService)通用:

I would like to modify this implementation so that it takes in the Type of the class that instantiates it (the underlying logger, LogWriter in this case, would be a singleton). So either make this implementation (and the interface ILoggingService) generic:

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

或添加其他构造函数的参数:

Or add an additional constructor parameter:

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到类的构造函数,他们正在努力的,而不是添加另一条线路我们的团结config来注册每个他们正在类

Is there a way to configure this once in Unity when registering our types? I'd like to avoid having to add an entry for every class that wants to log. Ideally, if someone wants to add logging to a class in our project, they'd just add an ILoggingService to the constructor of the class they are working in, instead of adding another line to our unity config to register each class they are working on.

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

推荐答案

是的,你可以使用:


container.RegisterType(typeof运算(IMyGenericInterface<>)的typeof(MyConcreteGenericClass<>));

这篇关于通用依赖注入与团结的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆