Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use UnityResolver in Console App?

I have the following resolver in my WebApi project:

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

However in a console app, I don't have HttpContiguration. How can I tell my unity container to use this DependencyResolver from my console app?

like image 709
RobVious Avatar asked Aug 21 '16 15:08

RobVious


People also ask

What is unity registration?

Registration is how you control Unity to do it 'Your' way. When you register a Type , you are instructing Unity to create and initialize an instance of that Type in a very particular way.

What is container resolver unity?

You can use the Unity container to generate instances of any object that has a public constructor (in other words, objects that you can create using the new operator). When you call the Resolve method and specify the type that is not registered, the container simply generates and returns an instance of that type.

What is dependency injection unity?

Dependency injection is a design pattern and an implementation of the inversion of control design principle. It helps simplify and automate the wiring of components in complex applications. It helps achieve component isolation, something that is important for unit-testing.


2 Answers

There might be a better way, but I do my registrations, and then let the container resolve 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 ProgramStarter class.

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.
    }
}
like image 80
smoksnes Avatar answered Oct 26 '22 22:10

smoksnes


You don't. The UnityResolver exists to interact with the MVC framework. A console application is no framework and there are no framework types that a Console Application tries to create for you. Since there is no framework, no special hooks are required to use a DI container in a console application. You simply create the container and have one container.Resolve call to construct the object graph and call the method on the resolved object.

like image 41
Steven Avatar answered Oct 26 '22 22:10

Steven