如何替换Autofac中的IServiceCollection扩展方法?

问题描述 投票:0回答:1

我正在使用 ASP.Net Core 2.1 构建一个应用程序,并且使用 autofac 而不是内置 DI 容器。

现在我有一个疑问:如果我有一个为 IServiceCollection 提供扩展方法的库,我如何在 autofac 中使用它?

就我而言,我想添加 Refit 库来创建一些 REST 客户端。从文档来看,应该使用以下扩展方法将客户端添加到 DI 引擎中

services.AddRefitClient<ICountryRepository>()
                .ConfigureHttpClient(c => c.BaseAddress = new Uri(Configuration.GetSection("Apis:CountryApi:Url").Value));

如何使用 autofac 做同样的事情? 一般来说,有没有办法在 autofac 注册中使用 IServiceCollection 扩展方法?

我无法在ConfigureService方法中注册依赖项,因为我的项目分为多个dll,并且这种情况下的注册逻辑上属于另一个未引用的dll。 (模块的划分是我选择Autofac的原因之一)

谢谢

asp.net-core dependency-injection autofac refit
1个回答
0
投票

安装此 nuget 软件包:

Autofac.Extensions.DependencyInjection

用你的

IServiceCollection
做任何你需要做的事:

var services = new ServiceCollection();
services.AddWhatever();

然后,使用

Populate
将其添加到 Autofac 依赖项中:

var builder = new ContainerBuilder();
builder.RegisterType<MySweetClass>().As<MySweetInterface>();
builder.Populate(services);

像往常一样,注册的顺序很重要,因此您需要考虑相对于其他注册的

Populate
方法的调用位置。

© www.soinside.com 2019 - 2024. All rights reserved.