简体   繁体   中英

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.

您可以尝试为容器设置WithConcreteTypeDynamicRegistrations规则。

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