kirov-opensource / NAutowired

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

在aspnetcore的startup中如果无法访问autowired #18

Closed qinqoushui closed 3 years ago

qinqoushui commented 3 years ago

你好,service等,非controller,autowired无法被正确赋值,始终 为空,应该如何正确使用呢,目前没办法只好在HomeController中注入了一个属性,然后延时一段时间后再使用定时任务的方式来执行业务。

 [Service(NAutowired.Core.Models.Lifetime.Singleton)]
    public class FooService
    {
        IConfiguration _Configuration;
        public FooService(IConfiguration Configuration)
        {
            _Configuration = Configuration;
        }

        [Autowired]
        TcpServer tcpServer2 { get; set; }

        public async void Start()
        {
            await tcpServer2.Create(new Coldairarrow.DotNettySocket.BuildOption() { Port = int.Parse(_Configuration.GetSection("TCP:Port").Value) });
        }
    }
qinqoushui commented 3 years ago

已解决 //启动服务 TcpServer tcpServer; using (var scope = serviceProvider.CreateScope()) { tcpServer = scope.ServiceProvider.GetRequiredService(); DependencyInjection.Resolve(serviceProvider, tcpServer); } var appLifetime = app.ApplicationServices.GetRequiredService(); appLifetime.ApplicationStarted.Register(async () => { await tcpServer.Create(new Coldairarrow.DotNettySocket.BuildOption() { Port = int.Parse(Configuration.GetSection("TCP:Port").Value) }); });

FatTigerWang commented 3 years ago

由于Autowired属性的还原是在请求进来创建控制器对象时通过钩子来进行还原的,因此在Startup.cs中,是直接通过ASP.NET Core容器直接进行还原,而这时钩子无法正常工作,因此此处无法还原。这种情况下建议使用原生的构造函数注入依赖。

FatTigerWang commented 3 years ago

如果是Console程序,请看NET Core Console

qinqoushui commented 3 years ago

Console的没有问题。构造注入也是种办法。目前问题已经解决,谢谢。

qinqoushui commented 3 years ago

构造函数注入的示例(此方法对于TcpServer 内部依赖的其它属性注入无效。)

public class FooService
    {
        IConfiguration _Configuration;
        TcpServer _tcpServer;
        public FooService(IConfiguration Configuration, TcpServer tcpServer)
        {
            _Configuration = Configuration;
            _tcpServer = tcpServer;

        }

        public async void Start()
        {
            await _tcpServer.Create(new Coldairarrow.DotNettySocket.BuildOption() { Port = int.Parse(_Configuration.GetSection("TCP:Port").Value) });
        }
    }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider)
        {
...
//启动服务
            var appLifetime = app.ApplicationServices.GetRequiredService<Microsoft.Extensions.Hosting.IHostApplicationLifetime>();
            //使用service进行构造注入的方式处理
            FooService fooService;
            using (var scope = serviceProvider.CreateScope())
            {
                fooService = scope.ServiceProvider.GetRequiredService<FooService>();
            }
            appLifetime.ApplicationStarted.Register(() =>
          {
              fooService.Start();
          });