C# 在具有MVC 6的web API中未找到IServiceCollection
我正在使用MVC6的WebAPI,这里我要将存储库注入控制器,我们需要将它注册到DI容器中。打开Startup.cs文件 在C# 在具有MVC 6的web API中未找到IServiceCollection,c#,dependency-injection,asp.net-core-mvc,C#,Dependency Injection,Asp.net Core Mvc,我正在使用MVC6的WebAPI,这里我要将存储库注入控制器,我们需要将它注册到DI容器中。打开Startup.cs文件 在ConfigureServices方法中,添加突出显示的代码: using System; using System.Collections.Generic; using System.Linq; using Microsoft.Owin; using Owin; using TodoApi.Models; [assembly: OwinStartup(typeof(To
ConfigureServices
方法中,添加突出显示的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Owin;
using Owin;
using TodoApi.Models;
[assembly: OwinStartup(typeof(TodoApi.Startup))]
namespace TodoApi
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// Add our repository type
services.AddSingleton<ITodoRepository, TodoRepository>();
}
}
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用Microsoft.Owin;
使用Owin;
使用TodoApi.Models;
[程序集:OwinStartup(typeof(TodoApi.Startup))]
名称空间TodoApi
{
公共部分类启动
{
公共无效配置(IAppBuilder应用程序)
{
ConfigureAuth(app);
}
public void配置服务(IServiceCollection服务)
{
services.AddMvc();
//添加我们的存储库类型
services.AddSingleton();
}
}
}
它显示了错误
找不到类型或命名空间名称“IServiceCollection”(是否缺少using指令或程序集引用?)
添加对
Microsoft.Extensions.DependencyInjection
NuGet包的引用,然后我建议按照链接中的说明进行操作 我无意中问了这个问题,想寻求4.6+的帮助(似乎其他一些人也在寻求帮助),并创建了一个DefaultDependencyResolver,使其与MVC 5完全兼容,因此我希望这能帮助其他可能也这么做的人
对于这个问题,添加“Microsoft.Extensions.DependencyInjection”的第一个答案是正确的(因为IServiceCollection是在该包中定义的接口)
如果要将“Microsoft.Extensions.DependencyInjection”框架与MVC5或.NET framework 4.6+一起使用,则需要创建自定义依赖项解析程序
public class DefaultDependecyResolver : IDependencyResolver
{
public IServiceProvider ServiceProvider { get; }
public DefaultDependecyResolver(IServiceProvider serviceProvider)
=> this.ServiceProvider = serviceProvider;
public IDependencyScope BeginScope() => this;
public object GetService(Type serviceType)
=> this.ServiceProvider.GetService(serviceType);
public IEnumerable<object> GetServices(Type serviceType)
=> this.ServiceProvider.GetServices(serviceType);
public void Dispose() { }
}
注意:依赖项解析程序主要来自。这看起来像是一个依赖项问题,您可以发布您的project.json和完整的startup.cs文件吗?请查看我上面更新的问题,以及完整的startup.cs文件。@BanwariYadav
project.json
?可能是因为您没有使用运行新版本所需的新项目模板吗?您解决了这个问题吗?提供的链接非常有用且有用精确的但是,您应该在此处添加并解释内容,以防链接失效。这就是为什么苏不喜欢只有链接的答案。链接已经死了。
public static class IocConfig
{
public static void Register(HttpConfiguration config)
{
var services = new ServiceCollection()
.AddSingleton<ISearchService, SearchService>() // Add your dependencies
.BuildServiceProvider();
config.DependencyResolver = new DefaultDependecyResolver(services);
}
}
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
GlobalConfiguration.Configure(IocConfig.Register); // Added
}
}