autofac实例构造函数中的一个类

时间:2017-04-12 05:05:11

标签: c# configuration inversion-of-control autofac

我有下一个问题,我不明白为什么这个代码不起作用我认为是因为我不通过autofac注入构造函数类但我不知道怎么做,我们能帮助我做更好的方法吗?< / p>

在我添加生成器之前,如果我在服务工作中注释生成器代码,那么这项工作。

这是我的代码:

我有一个调用serv的类Controller:

$text = strip_tags($this->input->post('textarea'));
$words = count(explode(' ',$text));

这是服务和界面:

SET foreign_key_checks = 0;

生成器调用ohter类,工厂:

public class ZonesController : Controller
{
    private IZoneService zoneService;

    public ZonesController(IZoneService zoneService)
    {
        this.zoneService = zoneService;
    }

    [HttpGet]
    //Do work
}

工厂:

public class ZoneService : IZoneService
{
    private readonly IZoneRepository zoneRepository;
    private readonly IDtoFactory dtoFactory;
    private readonly ZoneGenerator zoneGenerator;

    public ZoneService(IZoneRepository zoneRepository, 
                              IDtoFactory dtoFactory,
                              ZoneGenerator zoneGenerator)
    {
        this.zoneRepository = zoneRepository;
        this.dtoFactory = dtoFactory;
        this.zoneGenerator = zoneGenerator;
    }

    public void Add(ZoneDetailDTO zone)
    {
         zoneGenerator.Generate(zone);
    }

    //Do Work
}

public interface IZoneService
{
    void Add(ZoneDetailDTO zone);
    //Do Methods
}

最后是我的容器:

public class ZoneGenerator
    {
        private readonly ZoneFactory zoneFactory;
        private readonly IZoneRepository zoneRepository;

        public ZoneGenerator(ZoneFactory zoneFactory, IZoneRepository zoneRepository)
        {
            this.zoneFactory = zoneFactory;
            this.zoneRepository = zoneRepository;
        }

        public void Generate(ZoneDetailDTO zoneModel)
        {
           var zone = zoneFactory.Create(zoneModel);
           zoneRepository.Add(zone);
        }
    }

1 个答案:

答案 0 :(得分:1)

您错过了向Load方法添加以下内容:

builder.RegisterType<ZoneGenerator>().AsSelf();
builder.RegisterType<ZoneFactory>().AsSelf();
builder.RegisterType<ZoneMapFactory>().AsSelf(); 
builder.RegisterType<ZoneScheduleFactory>().AsSelf();