Unity - How to create controller with dependencies manually?

526 Views Asked by At

I'm trying to create controller instance manually, but it has some dependencies by unity and now I'm just resolving all of them automatically and pass them to controller constructor

var c = new MyController(container.Resolve<IInterface1>(),
                         container.Resolve<IInterface2>())

Is it possible to create controller instance through Unity to get all dependencies automatically resolved?

1

There are 1 best solutions below

1
On

You can use InjectionConstructor to archive that. For example:

container.RegisterType<IInterface1, Implementation1>();
container.RegisterType<IInterface2, Implementation2>();

container.RegisterType<MyController>(new InjectionConstructor(
    container.Resolve<IInterface1>(), 
    container.Resolve<IInterface2>()));

Then combine this approach with ControllerFactory.