Search code examples
c#asp.net-mvcdependency-injectionscaffoldingasp.net-mvc-scaffolding

Where to register the context with dependency injection


According to this tutorial I should:

Register your context with dependency injection

The Tutorial describes that I should locate the method ConfigureServices() and put in there the code advised.

Here's my startup.cs:

using Microsoft.Owin;
using Owin;

[assembly: OwinStartupAttribute(typeof(MyProject.Startup))]
namespace MyProject
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
        }
    }
}

so I don't know where to correctly put the code.

Because the project isn't compatible with .net core 2.1, it was needed to change Project->Property to .Net Framework 4.6.1 and install packages Microsoft.EntityFrameworkCore.SqlServer and Microsoft.EntityFrameworkCore.Tools

I tried to add the dependency injection to global.asax.cs file as follows:

protected void Application_Start()
        {
            var services = new ServiceCollection();
            ConfigureServices(services);
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
}

private void ConfigureServices(IServiceCollection services)
    {
        var connection = @"Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;ConnectRetryCount=0";
        services.AddDbContext<BloggingContext>(options => options.UseSqlServer(connection));
    }

I succeeded with the step and created the controller and it works, but I haven't chosen the right context (BloggingContext), so it created second database. So, I need to create a controller with BloggingContext, do you know how?


Solution

  • Whilst using .NET Core tooling with full framework works quite well, if you have to use MVC5 and full framework I would not try to work it that way round.

    There are many .NET 4.6.1 dependency injection frameworks, in this example I will use Autofac.

    • Install the NuGet packages Autofac and Autofac.Mvc5.
    • Add an AutofacRegistration.cs class to the App_Start folder
    • In the Application_Start() method in Global.asax add the line AutofacRegistration.BuildContainer();

    Your AutofacRegistration class is where you wire up all your dependencies for dependency injection. The full docs are here https://autofaccn.readthedocs.io/en/latest/integration/mvc.html

    public class AutofacRegistration
    {
        public static void BuildContainer()
        {
            var builder = new ContainerBuilder();
    
            // Register your MVC controllers
            builder.RegisterControllers(typeof(MvcApplication).Assembly);
    
            // Now grab your connection string and wire up your db context
            var conn = ConfigurationManager.ConnectionStrings["BloggingContext"];
            builder.Register(c => new BloggingContext(conn));
    
            // You can register any other dependencies here
    
            // Set the dependency resolver to be Autofac.
            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
    }
    

    This is assuming your BloggingContext has a constructor that takes the connection string as a parameter and passes it to the base class. Something like

    public class BloggingContext : DbContext
    {
        public BloggingContext(string connectionString) : base(connectionString)
        {
        }
    }
    

    There is loads more in the documentation about scope etc that is worth reading but this should be the nuts and bolts of it.