vendredi 2 décembre 2016

Dependency Injection In Class Library

Having a solution with two projects I've ran into a DI problem. The solution consists of a class library and a WebApi2 app(which consumes the class library and exposes an api).

I've defined a Autofac.module in the class library which sets up all the DI in the project.

In the WebApi2 project I create the DI container (using Autofac.WebApi2) and load the module from the class library. Now when the api controllers in the WepApi2 project requests services in the class library they get created with all their dependencies, this all works great!

The problem is that I now in the class library need to instantiate some classes from a string(that eventually comes from the DB), as far as I know the only way to do this i by using reflection, so I do like this:

var ruleType = Type.GetType(rule.RuleImplementation.Implementation);
var rule = (IRule)Activator.CreateInstance(ruleType,param1,param2);

The problem is that the class implementing the IRule interface also has dependencies which need to get resolved, and this is what made me banging my on my keyboard for a while now.

Is it possible to somehow use reflection and autoFac together to instantiate the objects? I still need to be able to pass my params into the object as well.

... Or is there a way to somehow access the container (which was created in the webApi2 assembly) and use that to resolve it? I guess this would be some sort of service pattern which I believe is considered an anti pattern.

How do I proceed? All input is very appreciated.





Aucun commentaire:

Enregistrer un commentaire