kirov-opensource / NAutowired

ASP.NET CORE Field Injection Implement
MIT License
77 stars 16 forks source link

consoleHost.GetService会强行调用构造函数 #17

Closed qinqoushui closed 3 years ago

qinqoushui commented 3 years ago

你好,consoleHost.GetService会强行调用构造函数,这将导致无法在外部代码(非AutoWired注入方式)中获取已通过service管理的单例 ,例如在单元测试为EmbeddedChannel设置handler时。这个时候是推荐使用包括 这个service的类的属性来实现吗?例如 SerializerFactory._controllerFactory

 [Service(Lifetime.Singleton)]
    public class ControllerFactory : IControllerFactory
    {
}

 [Service(Lifetime.Singleton)]
    public class SerializerFactory : ISerializerFactory
    {
        public SerializerFactory()
        {
            Console.WriteLine("new SerializerFactory");
        }

        [Autowired()]
        IControllerFactory _controllerFactory;
}

 [Service]
    public class SDKPacketHandler : SDKPacketBaseHandler, IPacketHandler<SDKPacket>
    {

        [Autowired]
        IControllerFactory _controllerFactory;
}

 protected override SDKPacket initTestData()
        {
            //会立即导致一次ControllerFactory实例化
            consoleHost.GetService<SerializerFactory>();
            //因为ControllerFactory声明为[Service(Lifetime.Singleton)],此时不会导致实例化
            consoleHost.GetService<Protocol.Wigend.Handlers.SDKPacketHandler>();
            //再次导致ControllerFactory实例化
            var controllerFactory = consoleHost.GetService<ControllerFactory>();
            if (controllerFactory == null)
                throw new Exception("未找到服务ControllerFactory");
}
qinqoushui commented 3 years ago

我使用的问题,修改成接口就不会导致二次实例化了

 var controllerFactory = consoleHost.GetService<IControllerFactory>();
            if (controllerFactory == null)
                throw new Exception("未找到服务ControllerFactory");