How to register multiple implementations of the same interface in Asp.Net Core?

前端 未结 24 1947
不思量自难忘°
不思量自难忘° 2020-11-22 10:16

I have services that are derived from the same interface.

public interface IService { }
public class ServiceA : IService { }
public class ServiceB : IService         


        
24条回答
  •  无人共我
    2020-11-22 11:06

    My solution for what it's worth... considered switching to Castle Windsor as can't say I liked any of the solutions above. Sorry!!

    public interface IStage : IStage { }
    
    public interface IStage {
          void DoSomething();
    }
    

    Create your various implementations

    public class YourClassA : IStage { 
        public void DoSomething() 
        {
            ...TODO
        }
    }
    
    public class YourClassB : IStage { .....etc. }
    

    Registration

    services.AddTransient, YourClassA>()
    services.AddTransient, YourClassB>()
    

    Constructor and instance usage...

    public class Whatever
    {
       private IStage ClassA { get; }
    
       public Whatever(IStage yourClassA)
       {
             ClassA = yourClassA;
       }
    
       public void SomeWhateverMethod()
       {
            ClassA.DoSomething();
            .....
       }
    

提交回复
热议问题