简体   繁体   中英

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

是的,你可以使用:

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

In your case, when there's simple direct generic-param--to--generic-param mapping the Unity maybe actually handles that, but I doubt that any more advanced cases are not handled, because something at some point of time must provide the mapping of generic-parameters between the types (liek reordering Key-Value vs. Value-Key etc).

If Dave's answer is not enough, I'm fairly sure that you could write a plugin to Unity/ObjectBuilder that would register a new strategy or set of strategies that would cover just any type mapping you would like, including automatic assembly scanning or materialization of generics.

See the series of articles at http://www.orbifold.net/default/unity-objectbuilder-part-ii/ and the section near

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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