question

75753850 avatar image
0 Votes"
75753850 asked BruceZhang-MSFT edited

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

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?

windows-server-iisdotnet-aspnet-mvc
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

BruceZhang-MSFT avatar image
0 Votes"
BruceZhang-MSFT answered BruceZhang-MSFT edited

Hi @75753850 ,

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


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.