How can I use dependency injection in asp.net mvc?

丁丁大魔王 81 Reputation points
2022-04-11T05:51:06.997+00:00

As title said, I want to use dependency injection in MVC5 like asp.net core. But MVC5 doesn't have start up and those service configuration. How can I do that?

Internet Information Services
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,296 questions
0 comments No comments
{count} votes

Accepted answer
  1. Bruce Zhang-MSFT 3,736 Reputation points
    2022-04-11T06:17:53.343+00:00

    Hi @丁丁大魔王 ,

    You can use Microsoft extensions .NET core DI to achieve Dependency Injection. using Microsoft.Extensions.DependencyInjection.

    Use a configuration class like asp.net core:

    public void Configuration(IAppBuilder app)  
    {  
        // We will use Dependency Injection for all controllers and other classes, so we'll need a service collection  
        var services = new ServiceCollection();  
      
        // configure all of the services required for DI  
        ConfigureServices(services);  
      
        // Configure authentication  
        ConfigureAuth(app);  
      
        // Create a new resolver from our own default implementation  
        var resolver = new DefaultDependencyResolver(services.BuildServiceProvider());  
      
        // Set the application resolver to our default resolver. This comes from "System.Web.Mvc"  
        //Other services may be added elsewhere through time  
        DependencyResolver.SetResolver(resolver);  
    }  
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Bruce Zhang

    0 comments No comments

0 additional answers

Sort by: Most helpful