Factory method with DI and IoC

后端 未结 6 663
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 15:30

I am familiar with these patterns but still don\'t know how to handle following situation:

public class CarFactory
{
     public CarFactory(Dep1,Dep2,Dep3,De         


        
6条回答
  •  Happy的楠姐
    2020-11-22 15:41

    Answering your comment about code example with Composition Root. You can create following and this is not a Service Locator.

    public class CarFactory
    {
        private readonly Func carFactory;
    
        public CarFactory(Func carFactory)
        {
           this.carFactory = carFactory;
        }
    
        public ICar CreateCar(Type carType)
        {
            return carFactory(carType);
     }
    

    and this is how look your Composition Root using Unity DI container :

    Func carFactoryFunc = type => (ICar)container.Resolve(type);
    container.RegisterInstance(new CarFactory(carFactoryFunc));
    

提交回复
热议问题