【问题标题】:.NET Core with Autofac DI.NET Core 与 Autofac DI
【发布时间】:2017-06-13 09:51:04
【问题描述】:

我想将Autofac 集成到我的 API。解决方案在多个项目上拆分,以便一切都保持解耦。我已经像这样设置了我的配置服务:

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    ...
    ...

    // Autofac
    var builder = new ContainerBuilder();

    builder.RegisterType<RouteRepository>().As<IRouteRepository>();

    builder.Populate(services);
    ApplicationContainer = builder.Build();
    return new AutofacServiceProvider(ApplicationContainer);
}

但是,现在集成了此代码后,我的 API 将不再启动。如果我在调试模式下启动它,我不会收到任何错误,但我也没有得到响应。

API 登陆路线非常简单:

public IActionResult GetIndex()
{
    return Ok("You are seeing this because controller is working!");
}

另外,可能与问题有关的是RouteRepository 将一个变量作为构造函数中的参数,我不知道在哪里可以定义要传递的内容?默认没有配置文件。

【问题讨论】:

  • ConfigureServices 是否调用services.AddMvc()Configure 是否调用UseMvc()
  • 是的,我只是从显示的代码中省略了它,因为我认为它不相关
  • 如果你的仓库在构造函数中接受参数,你必须在启动时定义依赖:builder.RegisterType&lt;RouteRepositoryParameter&gt;().As&lt;IRouteRepositoryParameter&gt;();

标签: c# .net dependency-injection .net-core autofac


【解决方案1】:

如果你说你的RouteRepository 有一个依赖项,那么你必须通知Autofac 容器如何解决这个问题:

// singletone
builder.RegisterInstance(new TaskRepository())
   .As<ITaskRepository>();
// or instance based creation
builder.Register(c => new LogManager(DateTime.Now))
   .As<ILogger>();

或者Autofac 无法解析您的类型。

【讨论】:

    猜你喜欢
    • 2021-06-03
    • 2020-06-09
    • 2023-03-08
    • 2021-11-17
    • 2023-02-08
    • 2021-03-04
    • 2018-10-12
    • 2021-04-14
    • 1970-01-01
    相关资源
    最近更新 更多