Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic dependency injection with Unity

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...
}

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.
}

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.

We are using run time/code configuration, not XML

like image 938
Dan Avatar asked Dec 16 '22 12:12

Dan


1 Answers

Yes, you can use:

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

like image 100
DaveRead Avatar answered Dec 29 '22 09:12

DaveRead