Search code examples
c#dependency-injectioninversion-of-controldryioc

How to create an instance of a class and inject dependencies without registering it in DryIoc?


I need to create an instance of a class with some parameters without registering it in the container, as I often need to get some classes with the dependencies injected without them cluttering the container.

Here is an example:

interface IPrinter
{
    void Print(string text);
}
class ConsolePrinter : IPrinter
{
    public void Print(string text) => Console.WriteLine(text);
}
class Thing
{
    public Thing(IPrinter print, string otherParameter)
    {
        // ...
    }
}
class Program
{
    static void Main(string[] args)
    {
        var container = new Container();

        container.Register<IPrinter, ConsolePrinter>();

        // This throws.
        container.Resolve<Thing>(args: new object[] { "something something" });
    }
}

I get an exception: DryIoc.ContainerException: 'code: UnableToResolveUnknownService, which makes sense.

I can sure just do container.Register<Thing>(), but as said before, it would add an unwanted service to my container.


Solution

  • You may try to set WithConcreteTypeDynamicRegistrations rules for container.