【问题标题】:Dependeny Injection Error - Unable to resolve service ... for type while attempting to activate依赖注入错误 - 尝试激活时无法解析服务 ... 类型
【发布时间】:2019-12-20 12:24:15
【问题描述】:

我在测试 WebAPI 项目时遇到依赖注入错误

InvalidOperationException:尝试激活“EventsAPI.Controllers.EventsController”时无法解析“EF_Events.Models.EventDBContext”类型的服务。

我的解决方案中有两个独立的项目。 EF 项目和引用 EF 项目的 API 项目。

EventsController.cs(在 API 项目中)

public class EventsController : ControllerBase
{

    private readonly Services.IEventService _service;
    private readonly EventDBContext _eventContext;
    private readonly IEventRepository _eventRepository;

    public EventsController(EventDBContext context)
    {
        _eventContext = context;
        _eventRepository = new EventRepository(_eventContext);
        _service = new Services.EventService(_eventRepository);
    }

    // GET api/values
    [HttpGet]
    public ActionResult Get()
    {
        //   return new string[] { "value1", "value2" };
        var events = _service.GetAllEvents();
        return Ok(events);

    }
}

EventService.cs(在 API 项目中)

namespace EventsAPI.Services
{
    public class EventService : IEventService
    {
        private readonly IEventRepository _rep;

        public EventService(IEventRepository eventRepository)
        {
            _rep = eventRepository;
        }

        public List<Event> GetAllEvents()
        {
            return _rep.GetAllEvents();
        }

        //public Event GetEventDetail(int id)
        //{
        //    return _rep.GetEventDetail(id);

        //}
    }
}

Startup.cs(在 EF 项目中)

services.AddDbContext<EventDBContext>
            (options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
        services.AddScoped<IEventRepository, EventRepository>();

EventRepository.cs(在 EF 项目中)

public class EventRepository : IEventRepository
{

    private readonly EventDBContext _eventContext;

    public EventRepository(EventDBContext context)
    {
        _eventContext = context;
    }

    public List<Event> GetAllEvents()
    {
        return _eventContext.Events.ToList();
    }
}

不知道我做错了什么;我在这里和其他网站上检查了几篇文章。看起来我的 Startup.cs 是正确的,但它只是不工作。

【问题讨论】:

  • 确切的错误是这个 InvalidOperationException: Unable to resolve service for type 'EF_Events.Models.EventDBContext' while trying to activate 'EventsAPI.Controllers.EventsController'。
  • DefaultConnection 是一个有效的连接字符串吗?
  • 是的,它是有效的。我能够生成数据库。
  • 你有不止一个类叫EventDBContext
  • 我还要说,您可能需要尽快将整个项目放入 github 存储库中,因为此时它可能是任何东西:\

标签: c# asp.net-core dependency-injection asp.net-core-webapi


【解决方案1】:

将您的控制器构造函数更改为;

public EventsController(IEventDBContext context)
{
    _eventContext = context;
    _eventRepository = new EventRepository(_eventContext);
    _service = new Services.EventService(_eventRepository);
}

也是您的存储库构造函数;

public EventRepository(IEventDBContext context)
{
    _eventContext = context;
}

然后,DI 将注入正确的数据库上下文。

【讨论】:

    【解决方案2】:

    您在帖子的 cmets 中提到,在调试 startup.cs 中的断点时没有命中。

    您能否确认将 Startup 类添加到 program.cs 中的 WebHostBuilder 配置中?

    var host = new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>() // This line
            .Build();
    
        host.Run();
    

    编辑:

    控制器:

     private readonly Services.IEventService _service;
    
    
    public EventsController(IEventService service)
    {
        _service = service;
    }
    

    在 EF 项目中添加 ServiceCollectionExtension 类:

    public static IServiceCollection AddEFProject(this IServiceCollection services)
    {
    
        services.AddDbContext<YourDbContext>(o => o.UseSql //....);
        services.AddScoped<IRepo, Repo>();
        return services;
    }
    

    然后在您的其他项目中引用 EF 项目并将服务添加到集合中

    Startup.cs:

    services.AddEfProject();
    

    【讨论】:

    • 是的,我在我的 EF 项目的 Program.cs 中有那行
    • IEventService 是否已注册并添加到容器中? Services.AddScoped&lt;..&gt; ?此外,您不需要在控制器中注入所有内容,只需将您正在调用的服务即可。 IoC 容器负责其余的工作。它将在后台解析存储库和上下文。
    • EventRepository 的范围在 Startup.cs。但是,在调试时,上下文为空
    • 感谢代码我想我在原始帖子中遗漏了一些重要信息,它将进行编辑。我的解决方案中有 2 个项目,一个 EF 项目和一个引用 EF 项目的 API 项目。因此,因此,我不能仅将服务范围限定为存储库
    • ServiceCollectionExtensionPattern:在这种情况下,您需要将 ServiceCollectionExtension 添加到您的 EF 项目中。称它为“添加EfProjectName。然后在您的其他项目的启动中添加 Services.AddEfProjectName 以便这些服务也在容器中解析。见:dotnetcoretutorials.com/2017/01/24/…
    猜你喜欢
    • 1970-01-01
    • 2017-04-15
    • 1970-01-01
    • 2018-04-06
    相关资源
    最近更新 更多