简体   繁体   中英

Get resolved dependancies of IRepository with AutoFac

With interfaces set up like so:

public interface IRepository { };

public interface IFirstRepository : IRepository { };
public interface ISecondRepository : IRepository { };
public interface IThirdRepository : IRepository { };

And a Controller that needs some but not all of these repositories:

public class TestController : BaseController 
{
    private IFirstRepository mFirstRepository;
    private ISecondRepository mSecondRepository;
    // Standard DI for MVC 
    public TestController(IFirstRepository first, ISecondRepository second)
    {
        mFirstRepository = first;
        mSecondRepository = second;
    }
}

And BaseController looks like:

public class BaseController : Controller {
     public IEnumerable<IRepository> GetRepos()
     {
         // One solution is to use reflection 
         // to get all properties that are IRepositories.
         // Something along the lines of;
         return typeof(this).GetProperties().Where(prop=>prop is IRepository);

         // But is there a way to use the AutoFac context
         // to get the repos, rather than use reflection?
         // it surely already has that info since it
         // was able to call the constructor correctly?
     }
}

Is there a way BaseController can utilize the AutoFac context and existing info to get the collection of the IRepository instances requested by the TestController ?

Autofac surely already has that info since it was able to call the constructor with the correct instances.

NB: The only reason I don't just use reflection here is performance concerns.

There's not an easy way to do this out of the box. If you find yourself in this situation, generally it means you have an interface design problem. There's an FAQ walking through an example of why this is, as well as some options.

If you really, really need to do this, then I'd probably look at adding metadata to each of the registrations where you have a metadata entry for each controller requiring that particular repository, then filter at the constructor using the metadata filter attribute . Again, the FAQ I mentioned walks through this and shows examples.

But if it was me working in this system... I'd step back and look at my interface design to see how to get away from needing this sort of filter in the first place. If they all can't be treated equally (Liskov substitution principle) then it indicates there are different interfaces required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM