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?
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.
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.
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.
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.
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With