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>()
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);
Note. The tool for determining dependencies was taken mainly from here .
source share