Search code examples
c#tinyioc

TinyIoC register instance of unknown type


I'm trying to allow users of my library, which is internally wired up via tinyioc, to pass in their own implementation of an interface defined within my library which will then be resolved to whenever an instance is needed.

For example, the user can do this:

public class Logger : Things.ILogger
{
    // Implement members
    public void Log(string s)
    {
        ...
    }
}

var thing = new Things.ThingBuilder().WithLogger(new Logger()).Build();

Within my library I want to wire up the logger which is passed in. Something like:

namespace Things
{
    public class ThingBuilder()
    {
        private ILogger logger;

        public ThingBuilder WithLogger(ILogger logger)
        {
            this.logger = logger;
            return this;
        }

        public Thing Build()
        {
            TinyIocContainer container = new TinyIocContainer();
            container.Register(ILogger, logger); // I want this to be used 
                                                 // wherever an ILogger is needed

            ...
        }
    }    
}

However, I can't find a way TinyIoc will let me do this. Is this supported? I know that TinyIoc supports registering instances of types it knows about, but not if the type is unknown.


Solution

  • I worked around this in the end by manually passing the user-supplied instance of ILogger to wherever it was required in the library codebase. This is satisfactory as I think on reflection my initial expectations were unrealistic.