I am working with web API with MVC 6, here I am going in order to inject the repository into the controller, we need to register it with the DI container. Open the Startup.cs file.
In the ConfigureServices
method, going 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>();
}
}
}
Its showing the error...
The type or namespace name 'IServiceCollection' could not be found (are you missing a using directive or an assembly reference?)
Add a reference to the Microsoft.Extensions.DependencyInjection
NuGet package, and then I recommend doing what is explained in this link.
I stumbled to this question looking for help with 4.6+ (as it seems a few others were looking as well) and creating a DefaultDependencyResolver to make fully compatible with MVC 5, so I hope this helps others who may do the same.
The first answer is correct for this question to add "Microsoft.Extensions.DependencyInjection" (since the IServiceCollection is an interface defined within that package).
If you want to use the "Microsoft.Extensions.DependencyInjection" framework with MVC5 or .NET Framework 4.6+, you need to create a custom dependency resolver.
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 dependency resolver required. You can even wrap this into an "IocConfig" class to follow 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 just update the Application_Start
of your global.asax:
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
GlobalConfiguration.Configure(IocConfig.Register); // Added
}
}
Note: The dependency resolver was taken mostly from here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With