Search code examples
ioc-containerpartialautofacresolve

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);


Solution

  • I would say your design is sub optimal.

    You seem to be mixing to things. Dependency injection (using a container) should mainly be used for injecting service components into other components. Don't inject thing like entities, because it is not up to the container to manage their lifetime. Rather, inject a service that can manage entities for you, such as a repository. Although topic of discussion, I would neither inject a unit of work, but rather a factory for creating unit of works. This way your application manages the lifetime of the unit of work explicitly.