Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Microsoft.Extension.DependencyInjection in Asp.net Web Api2

I am trying to implement Asp.Net webApi project which is depending on a third-party framework that does a lot of stuff with HttpContext.Current which does not exists in Asp.net Core. That is why I could not create Asp.net Core Web Application targeting .net full framework.

So I created old-school Asp.net Web Application project with WebApi extension.

Now I am trying to use Microsoft.Extension.DependencyInjection framework with it.

I found this example for Asp.Net Mvc4 but my project is WebApi. That approach did not work. Can anyone provide link or code snippet for me to move forward?

P.S: When providing an example, please make sure it should not use OWIN framework. Because when I tried to use OWIN pipeline, the third-party library(closed source) is not working properly.

like image 435
telli Avatar asked May 15 '18 20:05

telli


People also ask

What is Microsoft Aspnet Web API?

ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the . NET Framework.

How do I add Entity framework to Web API?

In the New Project dialog, select Web in the left pane and ASP.NET Web Application (. NET Framework) in the middle pane. Name the project BookService and select OK. In the New ASP.NET Project dialog, select the Web API template.


1 Answers

I also found that example a while ago, i make it work perfect both in Asp.Net Mvc4 and WebApi2 project.

Use some IoC container (eg. Unity, Autofac) for WebApi project, the most important thing is implementing the interface IDependencyResolver to make your own dependency resolver.

Hers's my code snippet for WebApi project.

WebApiConfig

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        ...

        // using Microsoft.Extension.DependencyInjection here.
        Startup.Bootstrapper(config);
    }
}

Startup

public class Startup
{
    public static void Bootstrapper(HttpConfiguration config)
    {
        var provider = Configuration();
        var resolver = new DefaultDependencyResolver(provider);

        config.DependencyResolver = resolver;
    }

    private static IServiceProvider Configuration()
    {
        var services = new ServiceCollection();

        services.AddControllersAsServices(typeof(Startup).Assembly.GetExportedTypes()
            .Where(t => !t.IsAbstract && !t.IsGenericTypeDefinition)
            .Where(t => typeof(IHttpController).IsAssignableFrom(t)
                        || t.Name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase)));

        var serviceProvider = services.BuildServiceProvider();

        return serviceProvider;
    }
}

DefaultDependencyResolver

public class DefaultDependencyResolver : IDependencyResolver
{
    private IServiceScope serviceScope;
    protected IServiceProvider ServiceProvider { get; set; }

    public DefaultDependencyResolver(IServiceProvider serviceProvider)
    {
        this.ServiceProvider = serviceProvider;
    }

    public object GetService(Type serviceType)
    {
        return this.ServiceProvider.GetService(serviceType);
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        return this.ServiceProvider.GetServices(serviceType);
    }

    public IDependencyScope BeginScope()
    {
        serviceScope = this.ServiceProvider.CreateScope();
        return new DefaultDependencyResolver(serviceScope.ServiceProvider);
    }

    public void Dispose()
    {
        // you can implement this interface just when you use .net core 2.0
        // this.ServiceProvider.Dispose();

        //need to dispose the scope otherwise
        //you'll get a memory leak
        serviceScope?.Dispose();
    }
}

ServiceProviderExtensions

public static class ServiceProviderExtensions
{
    public static IServiceCollection AddControllersAsServices(this IServiceCollection services,
        IEnumerable<Type> controllerTypes)
    {
        foreach (var type in controllerTypes)
        {
            services.AddTransient(type);
        }

        return services;
    }
}
like image 80
Hin Liang Avatar answered Sep 20 '22 00:09

Hin Liang