Search code examples
asp.netentity-frameworkasp.net-web-apiasp.net-identityn-tier-architecture

Referencing in the context of asp.net Identity 2.0 separation


I try to separate one of my API projects into three different layers.

  • The API
  • Data access(repos + uow)
  • Data Entities
  • The API is using Asp.net Identity 2.0 with code from a sample I installed, just enough to work with OAuth Authorization.

    However, When I do this separation, sometimes I get an error telling me that I need to reference the third layer(entities) from my first layer. And I can't figure out why. That would break the whole purpose of the separation, right?

    For example, when I try to replace this line(from the API layer in Startup.Auth.cs, ConfigureAuth method)

    app.CreatePerOwinContext(ApplicationDbContext.Create);
    

    With

    app.CreatePerOwinContext(uow.CreateDbContext()) 
    

    A method that returns a new instance of the ApplicationDbContext.

    I would expect that context to be returned from my second layer, where my UnitOfWork is(which in turn gets the ApplicationDbContext from the data layer).

    Could someone please explain how this works?


    Solution

  • To solve your issue you need to start use Interfaces and any DI-framework. Here I can provide you with the code if you want to start using AutoFac (https://code.google.com/p/autofac/wiki/WebApiIntegration).

    When you installed AutoFac to your solution through Nuget. Add this part of code in your Global.asax.cs file.

    protected void Application_Start()
    {
        ...
        SetupAutoFac();
        ...
    }
    
    private static void SetupAutoFac()
    {
        var builder = new ContainerBuilder();
        builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
    
        var container = builder.Setup();
        var resolver = new AutofacWebApiDependencyResolver(container);
        GlobalConfiguration.Configuration.DependencyResolver = resolver;
    }
    

    Create this part of code in your BLL-layer:

    public static class AutoFacConfiguration
    {
        public static IContainer Setup(this ContainerBuilder builder)
        {
            REGISTER ALL YOUR SERVICES AND UOW HERE
    
            return builder.Build();
        }
    }
    

    After this you can inject every services Interface to your ApiControllers, and the the WebAPi will only have a reference to your BLL-layer or to the layer where you put all your interfaces.