IServiceCollection not found in web API with MVC 6

I work with web APIs with MVC 6, here I am going to embed the repository in the controller, we need to register it with the DI container. Open the Startup.cs file.

In the ConfigureServices method to add the highlighted code:

 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>(); } } } 

Shows an error ...

Could not find the name of the type or namespace "IServiceCollection" (are you missing the using directive or assembly references?)

+11
source share
2 answers

Add a link to the Microsoft.Extensions.DependencyInjection NuGet package, and then I recommend doing what is described in this link .

+9
source

I came across this question looking for help with 4. 6+ (as it seems some others were looking too) and creating a DefaultDependencyResolver for full compatibility with MVC 5, so I hope this helps others who can do the same.

The first answer is correct for this question to add "Microsoft.Extensions.DependencyInjection" (since IServiceCollection is the interface defined in this package).

If you want to use the "Microsoft.Extensions.DependencyInjection" infrastructure with MVC5 or the .NET Framework 4. 6+, you need to create your own dependency converter.

 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() { } } 

Then you can create the service provider and the required dependency resolver. You can even wrap this in the "IocConfig" class to follow the MVC5 conventions:

 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); } } 

Then you can simply update Application_Start your global.asax:

 public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { GlobalConfiguration.Configure(WebApiConfig.Register); GlobalConfiguration.Configure(IocConfig.Register); // Added } } 

Note. The tool for determining dependencies was taken mainly from here .

0
source

All Articles