Mvc simple dependency injection from service layer to data layer (three layer application)

545 Views Asked by At

I have to rewrite an old asp classic web application. I chose an architecture in three levels (tier/project = layer level)

  • Web: views and controllers, thin as much as possible. References service layer project.
  • Service: business logic. References data layer project.
  • Data: ado net queries, database connection and transaction management. No reference to other projects

In web layer I manage service layer injection with this class, simple DI

[assembly: OwinStartupAttribute(typeof(MyApp.Startup))]
namespace MyApp
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            var services = new ServiceCollection();
            ConfigureServices(services);
            var resolver = new DefaultDependencyResolver(services.BuildServiceProvider());
            DependencyResolver.SetResolver(resolver);
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersAsServices(typeof(Startup).Assembly.GetExportedTypes()
                .Where(t => !t.IsAbstract && !t.IsGenericTypeDefinition)
                .Where(t => typeof(IController).IsAssignableFrom(t)
                   || t.Name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase)));

            services.AddSingleton<IAuthenticationService, AuthenticationService>();
            services.AddSingleton<IChannelService, ChannelService>();
            //add more DI services here...
        }
    }
}

The web layer doesn't know anything of data layer so how do I inject data layer classes? I need at least to make available data layer in service layer but how do I make a class like the one above in service layer?

EDIT: possible solution from a comment now deleted. Also i found a interesting article about this argument here

https://asp.net-hacker.rocks/2017/03/06/using-dependency-injection-in-multiple-projects.html

create a extension class in service layer that adds data layer dependencies to IServiceCollection instance

namespace MyApp.Service
{
    public static class IServiceCollectionExtension
    {
        public static IServiceCollection AddDataQueries(this IServiceCollection services)
        {
            //services.AddTransient<IQuery, Query>();
            //...add here DI of other data services
            return services;
        }
    }
}

and in startup class

 services.AddSingleton<IAuthenticationService, AuthenticationService>();
 services.AddSingleton<IChannelService, ChannelService>();
 //add more DI services here...
 services.AddDataQueries();
 //add DI for other layers
0

There are 0 best solutions below