Allow dependency with autofac based on constructor parameter attribute

I am using Autofac. I want to add another dependency implementation based on the attribute that I am applying to the constructor parameter. For instance:

class CustomerRepository { public CustomerRepository([CustomerDB] IObjectContainer db) { ... } } class FooRepository { public FooRepository([FooDB] IObjectContainer db) { ... } } builder.Register(c => /* return different instance based on attribute on the parameter */) .As<IObjectContainer>(); 

Attributes will provide data, such as a connection string, which I can use to instantiate the correct object.

How can i do this?

+4
source share
2 answers

It looks like you want to provide different implementations of IObjectContainer before CustomerRepository and FooRepository . If so, the attributes can be a thin metal ruler . Instead, I will show you how to implement many implementations using Autofac.

(Calls such as .ContainerScoped() have been omitted for brevity.)

First, register a version of IObjectContainer for each connection string, naming the registration:

 builder .Register(c => new ObjectContainer(ConnectionStrings.CustomerDB)) .As<IObjectContainer>() .Named("CustomerObjectContainer"); builder .Register(c => new ObjectContainer(ConnectionStrings.FooDB)) .As<IObjectContainer>() .Named("FooObjectContainer"); 

Then, enable specific instances in the repository registration:

 builder.Register(c => new CustomerRepository( c.Resolve<IObjectContainer>("CustomerObjectContainer")); builder.Register(c => new FooRepository( c.Resolve<IObjectContainer>("FooObjectContainer")); 

This leaves the repositories without configuration information:

 class CustomerRepository { public CustomerRepository(IObjectContainer db) { ... } } class FooRepository { public FooRepository(IObjectContainer db) { ... } } 
+9
source

Bryan's answer is good enough if you have multiple repositories and they have few constructor options. But it’s hard to establish your root when you have a lot of them. This can be done by scanning the class metadata while resolving the interface. When you get information about your parameters, you can decide its actual implementation. See my answer here .

0
source

Source: https://habr.com/ru/post/1304571/


All Articles