skyhunter96
skyhunter96

Reputation: 143

.NET Core MVC Startup equivalent

I am wondering is, since I would like to implement dependency injection container for my web application (MVC) controllers. In .NET Core framework, I used to have a Startup.cs file inside the project which was used for adding transients and dependency injections to the container, also for DbContext:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        services.AddDbContext<LibraryContext>();
        services.AddTransient<IGetBooksCommand, EfGetBooksCommand>();
    }

I would like to know how could I achieve this in the full .NET Framework.

Upvotes: 1

Views: 647

Answers (2)

Mukesh Modhvadiya
Mukesh Modhvadiya

Reputation: 2178

.Net core Mvc supports built in dependency injection and it is capable of injecting dependencies in the controllers. So dependency registered as below can be used in controller

services.AddTransient<IGetBooksCommand, EfGetBooksCommand>();

However built in dependency injection functionality can be replaced by more mature DI frameworks. And that is very simple as below is the example for using Autofac

public IServiceProvider ConfigureServices(IServiceCollection services) {
    var builder = new ContainerBuilder();
    builder.Populate(services);
    builder.RegisterType<EfGetBooksCommand>().As<IGetBooksCommand>();
    var container = builder.Build();
    return new AutofacServiceProvider(container);
}

ConfigureServices method now returns IServiceProvider instead of void. And dependencies will now be resolved using Autofac.

ref :

Dependency injection into controllers in ASP.NET Core

.Net Core Dependency Injection

Upvotes: 1

Cyber Progs
Cyber Progs

Reputation: 3873

Prior to .Net Core, there is no built-in support for dependency injection the only way to get it was through the use of third-party frameworks such as Autofac, Castle Windsor, Unity, Ninject ..etc

You can check any of these frameworks and use them in your project.

Upvotes: 2

Related Questions