Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can autofac do partial Resolve?

I seem to need this a lot.

Let's say I have a class with constructor taking several arguments. Some of these can be resolved by registering components. But the rest are instances created during runtime (e.g. fetching an entity from database).

Can Autofac deal with these situations in a nice way? Or is my design sub-optimal?

To clarify, I have classes that have constructors like this:

public MyClass(IService1 service1, IService2 service2, Data1 data1, Data2 data2)
{
//...
}

And I would like to do something like this:

container.Resolve<MyClass>(data1, data2);

like image 723
Kugel Avatar asked Jun 07 '11 12:06

Kugel


People also ask

What is resolve in Autofac?

After you have your components registered with appropriate services exposed, you can resolve services from the built container and child lifetime scopes. You do this using the Resolve() method: var builder = new ContainerBuilder(); builder. RegisterType<MyComponent>(). As<IService>(); var container = builder.

Why should I use Autofac?

AutoFac provides better integration for the ASP.NET MVC framework and is developed using Google code. AutoFac manages the dependencies of classes so that the application may be easy to change when it is scaled up in size and complexity.

What is Autofac dependency injection?

Autofac is an open-source dependency injection (DI) or inversion of control (IoC) container developed on Google Code. Autofac differs from many related technologies in that it sticks as close to bare-metal C# programming as possible.


1 Answers

You can handle this elegantly by registering a factory method in the Autofac container. You resolve the factory method, and then use it to create instances with your runtime dependencies. You can do this yourself by registering and resolving delegates or custom factory types. However, Autofac has explicit support for delegate factories.

There is not enough information to comment on your design. I'll leave that to you :)

like image 103
bentayloruk Avatar answered Sep 18 '22 03:09

bentayloruk