c# - How to resolve different services in different controllers? -


i have 2 mvc controllers.

both controllers have dependency on ifilecontainer interface.

in 1 controller want resolve fsfilecontainer , in second controller want resolve ftpfilecontainer.

register:

    servicecollection.addtransient<ifilecontainer, fsfilecontainer>();     servicecollection.addtransient<ifilecontainer, ftpfilecontainer>(); 

how resolve container in case?

the easiest way use factory instead asp.net core ioc container doesn't support named dependencies or use 3rd party ioc container supports it.

public class filecontainerfactory : ifilecontainerfactory  {     private readonly iserviceprovider provider;     public class filecontainerfactory(iserviceprovider provider)     {         this.provider = provider;     }      public ifilecontainer createfilesystemcontainer()      {         // resolve via built in ioc         return provider.getservice<fsfilecontainer>();     }      public ifilecontainer createftpcontainer()      {         // resolve via built in ioc         return provider.getservice<ftpfilecontainer>();     } } 

then inject ifilecontainerfactory controller.

an alternative mark interfaces marker interface , register/inject these

// defines no new methods or properties, inherits , acts marker public interface ifsfilecontainer : ifilecontainer {} public interface iftpfilecontainer : ifilecontainer {}  public class fsfilecontainer : ifsfilecontainer {     ... } 

in startup.cs

services.addtransient<ifsfilecontainer, ifilecontainer>(); services.addtransient<iftpfilecontainer, ifilecontainer>(); 

Comments

Popular posts from this blog

sequelize.js - Sequelize group by with association includes id -

android - Robolectric "INTERNET permission is required" -

java - Android raising EPERM (Operation not permitted) when attempting to send UDP packet after network connection -