Использование autofac в ядре asp.net 2.2 - PullRequest
1 голос
/ 06 мая 2019

Я пытаюсь использовать последнюю версию Autofac с проектом asp.net core 2.2.Однако документация по autofac, похоже, устарела.Я пытаюсь использовать autofac без ConfigureContainer:

// ConfigureServices is where you register dependencies. This gets
  // called by the runtime before the Configure method, below.
  public IServiceProvider ConfigureServices(IServiceCollection services)
  {
    // Add services to the collection.
    services.AddMvc();

    // Create the container builder.
    var builder = new ContainerBuilder();

    // Register dependencies, populate the services from
    // the collection, and build the container.
    //
    // Note that Populate is basically a foreach to add things
    // into Autofac that are in the collection. If you register
    // things in Autofac BEFORE Populate then the stuff in the
    // ServiceCollection can override those things; if you register
    // AFTER Populate those registrations can override things
    // in the ServiceCollection. Mix and match as needed.
    builder.Populate(services);
    builder.RegisterType<MyType>().As<IMyType>();
    this.ApplicationContainer = builder.Build();

    // Create the IServiceProvider based on the container.
    return new AutofacServiceProvider(this.ApplicationContainer);
  }

, но сигнатура метода ConfigureServices отличается в ядре asp.net 2.2

public void ConfigureServices(IServiceCollection services)
{
}

, тип возвращаемого значения отсутствует.Кто-нибудь знает, как использовать autofac в ядре asp.net 2.2?

1 Ответ

3 голосов
/ 06 мая 2019

Вам необходимо использовать этот пакет:

Autofac.Extensions.DependencyInjection

В вашем файле program.cs просто используйте следующие строки кода:

    public static IWebHostBuilder CreateWebHostBuilder(string[] args)
    {
        return WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .ConfigureServices(services => services.AddAutofac());
    }

В вашем файле startup.cs создайте метод с именем

    public void ConfigureContainer(ContainerBuilder builder)
    {
    }

и используйте «builder» для регистрации того, что вы хотите.Autofac сам найдет этот метод.

Вам больше не нужно вызывать builder.Build().

После замечаний, чтобы выполнить рекуррентный код с введенными значениями, вам нужнодобавить :

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddHostedService<MyHostedService>();
    ...
}

public class MyHostedService : IHostedService
{
    private Timer _timer;
    private IInjectedService _myInjectedService;

    public MyHostedService(IServiceProvider services)
    {
        var scope = services.CreateScope();

        _myInjectedService = scope.ServiceProvider.GetRequiredService<IInjectedService>();
    }

    public Task StartAsync(CancellationToken cancellationToken)
    {
        _timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromMinutes(5));

        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        _timer?.Change(Timeout.Infinite, 0);

        return Task.CompletedTask;
    }

    private async void DoWork(object state)
    {
        _myInjectedService.DoStuff();
    }
}
...