Keyed delegate factories with runtime constructor parameters?

前端 未结 2 1865
别那么骄傲
别那么骄傲 2021-02-05 10:42

Lets say I have the following service and components:

public interface IService
{
    void DoWork();
}

public class ServiceA : IService
{
    private readonly s         


        
2条回答
  •  萌比男神i
    2021-02-05 11:38

    You can use Interface Segregation.

    public interface IService
    {
        void DoWork();
    }
    
    public interface IServiceA : IService
    {
    }
    
    public interface IServiceB : IService
    {
    }
    
    public class ServiceA : IServiceA
    {
        private readonly string _name;
    
        public ServiceA(string name)
        {
            _name = name;
        }
    
        public void DoWork()
        {
            //ServiceA DoWork implementation
        }
    }
    
    public class ServiceB : IServiceB
    {
        private readonly string _name;
    
        public ServiceB(string name)
        {
            _name = name;
        }
    
        public void DoWork()
        {
            //ServiceB DoWork implementation
        }
    }
    

    Then, you can inject delegate factories like so:

    public class ClientA
    {
        public ClientA(Func serviceAFactory, Func serviceBFactory)
        {
            this.serviceAFactory = serviceAFactory;
            this.serviceBFactory = serviceBFactory;
        }
    
        public CreateServices()
        {
            var runTimeName = "runTimeName";
            var serviceA = this.serviceAFactory(runTimeName);
            var serviceB = this.ServiceBFactory(runTimeName);
        }
    }
    

    Autofac will generate a delegate factory for each interface you register:

    public class MyModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType()
                .As()
                .As();
    
            builder.RegisterType()
                .As()
                .As();
        }
    }
    

提交回复
热议问题