0

I have a package (it's name is Tree), Tree contains 10 internal services (interfaces) and they are resolved by Autofac. Tree contains 2 external services:

  • TreeCommand

  • TreeQuery

I want to use multiple Trees in my application.

  • StudentTree

  • TeacherTree

  • CompanyTree etc.

Each implementation can use different component registrations (for sub services)

How can I implement this kind of requirement by Autofac?

My solution looks a little weird without multiple containers:

Sample registration: (It is simplified version of original)

foreach (var domainInfo in domainInfoList)
{
    var domainInfoParameter = new NamedParameter("domainInfo", domainInfo);
    var domain = domainInfo.Domain;

    builder.RegisterType<TreeFactory>()
           .Named<TreeFactory>(domain)
           .WithParameter(domainInfoParameter)
           .SingleInstance();


    builder.RegisterType<SqlTreeRepository>()
           .Named<ITreeRepository>(domain)
           .WithParameter(domainInfoParameter);

    builder.RegisterType<TreeCommandService>()
           .Named<TreeCommandService>(domain)
           .WithParameter(domainInfoParameter);


    builder.RegisterType<TreeQueryService>()
           .Named<TreeQueryService>(domain)
           .WithParameter(domainInfoParameter);
}

Sample resolving:

 container.ResolveNamed<TreeFactory>("Teacher");
 container.ResolveNamed<TreeCommand>("Student");
 container.ResolveNamed<TreeQuery>("Company");

What is the best practise in Autofac for this kind of requirement?

Cyril Durand
  • 15,834
  • 5
  • 54
  • 62
Oguz Karadenizli
  • 3,449
  • 6
  • 38
  • 73
  • Could you explain a little more how do you resolve your service ? if you need multiple named registration, your solution looks good to me. – Cyril Durand Feb 17 '18 at 07:04
  • You may be running into [this FAQ](http://autofac.readthedocs.io/en/latest/faq/select-by-context.html) - trying to treat components the same that actually aren't interchangeable. – Travis Illig Feb 18 '18 at 18:07

0 Answers0