How to use UnityResolver in a console application?

I have the following resolver in my WebApi project:

 config.DependencyResolver = new UnityResolver(container); // HttpConfiguration config

However, in the console application, I do not have an HttpContiguration. How can I tell the unity container to use this DependencyResolver from my console application?

+4
source share
2 answers

It may be better, but I do the registration, and then let the container allow my "first" class.

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Registering dependencies ...");
        var container = new UnityContainer();
        container.RegisterType<ProgramStarter, ProgramStarter>(); // Register a class that continues your program.

        // Do your registrations.
        RegisterTypes(container);

        // Let Unity resolve ProgramStarter and create a build plan.
        var program = container.Resolve<ProgramStarter>();

        Console.WriteLine("All done. Starting program...");
        program.Run();
    }
}

And my class ProgramStarter.

public class ProgramStarter
{
    private readonly IService _service;

    public ProgramStarter(IService service)
    {
        // Unity has created this instance and resolved all dependencies.
        _service= service;
    }

    public void Run()
    {
        // Do what you want to do.
    }
}
+5
source

. UnityResolver MVC. , . , DI . container.Resolve .

+3

Source: https://habr.com/ru/post/1651942/


All Articles