开发者

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 runtim开发者_开发知识库e (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);


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜