首页 > 解决方案 > 如何将 Nancy 与 Autofac 和 ASP.NET Core windows 服务集成

问题描述

让我尽量保持简单。我的最终目标是创建windows service使用asp.net core 2.1Nancy框架。

经过大量研究,我发现以下步骤

  1. 设置 Windows 服务 - https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/windows-service?view=aspnetcore-2.1

  2. 将 Nancy 连接到 .net 核心应用程序

问题陈述

我的 Windows 服务正在使用使用DI.net standard开发的类库。Autofac

现在我如何整合Autofac而不是Nancy's tiny IOC container

我尝试安装nuget

    Install-Package Nancy.Bootstrappers.Autofac -Version 2.0.0-clinteastwood

并且,编写代码如下

   protected override void ConfigureApplicationContainer(ILifetimeScope container)
   {

    _services.Configure<Settings>(_configuration.GetSection("MySettings"));
    var deviceId = _configuration["Settings:DeviceId"];

    var containerFactory = new ContainerFactory();

    container.Update(builder =>
    {
        builder.RegisterInstance(containerFactory).As<IContainerFactory>();
        containerBuilder.Register(c => new Engine(containerFactory));
        containerBuilder.Register(i => 
         new HubClient(deviceId, containerFactory))
          .As<HubClient>().SingleInstance();
    });
    base.ConfigureApplicationContainer(container);
}

而且,在这里我想注入我的类实例。但如何?

   public static void Main(string[] args)
    {
        var isService = !(Debugger.IsAttached || args.Contains("--console"));
        var builder = CreateWebHostBuilder(args.Where(arg => arg != "--console").ToArray());

        if (isService)
        {
            var pathToExe = Process.GetCurrentProcess().MainModule.FileName;
            var pathToContentRoot = Path.GetDirectoryName(pathToExe);
            builder.UseContentRoot(pathToContentRoot);
        }

        var host = builder.Build();

        if (isService)
        {
            //this line fails
             IContainerFactory containerfactory = host.Services.GetService<IContainerFactory>();
            host.RunAsCustomService();
        }
        else
        {
            host.Run();
        }
    }

如何获取/注入EngineHubClient实例?

标签: c#asp.net-coredependency-injectionautofacnancy

解决方案


推荐阅读