How to use dependency injection in ASP. Net web forms

Time:2021-7-21

Dependency injection technology is to inject an object into an object that needs it. At the same time, it is also an implementation of control inversion. Obviously, it can decouple objects and make it easier to test and maintain. The principle of dependency injection has already pointed out that the high-level module of an application program does not depend on the low-level module, Instead, it should rely on abstractions or interfaces.

stay.Net Framework 4.7.2Support for dependency injection is introduced inASP.Net Web FormsThis article will discuss how to use the dependency injection mechanism in ASP. Net web forms.

Create webform project

When using dependency injection in ASP. Net web forms, you must remember to set the project framework above 4.7.2, or right-click the project and select it on the property panel4.7.2edition.

You can also make the following settings directly in web.config.

...

Next, you can install it through nugetAspNet.WebFormsDependencyInjection.UnityPackage, which can be downloaded through visual studio 2019NuGet package managerVisual interface installation or throughNuGet package managerCommand line tools enter the following command:

dotnet add package AspNet.WebFormsDependencyInjection.Unity

Create entities and interfaces

Now create an entity class called author and the iauthorrepository interface.

public class Author
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

    public interface IAuthorRepository
    {
        bool Create(Author author);
        Author Read(int id);
        List Read();
    }

Then use the authorrepository class to implement the iauthorrepository interface. The code is as follows:

public class AuthorRepository : IAuthorRepository
    {
        public bool Create(Author author)
        {
            throw new System.NotImplementedException();
        }
        public Author Read(int id)
        {
            throw new System.NotImplementedException();
        }
        public List Read()
        {
            throw new System.NotImplementedException();
        }
    }

Create container and type registration

Now let’s createDependency injection container, and then inject the type we want. The following code is used to create theUnity Container

var container = this.AddUnity();

Then in the application_ Start event for objectDependency configuration, as shown in the following code:

container.RegisterType();

By the way, remember to introduce the following two namespace.

  • AspNet.WebFormsDependencyInjection.Unity

  • Unity

The following is the complete code of global class, for reference only.

using Microsoft.AspNet.WebFormsDependencyInjection.Unity;
using System;
using System.Web;
using System.Web.Optimization;
using System.Web.Routing;
using Unity;

namespace WebformsDIDemo
{
    public class Global : HttpApplication
    {
        void Application_Start(object sender, EventArgs e)
        {
            var container = this.AddUnity();
            container.RegisterType();
            // Code that runs on application startup
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}

WebForms uses dependency injection

Now that the container and object dependencies are configured, how can we use them in page? You can refer to the following code.

public partial class _Default : Page
    {
        private IAuthorRepository _authorRepository;

        public _Default(IAuthorRepository authorRepository)
        {
            _authorRepository = authorRepository;
        }

        protected void Page_Load(object sender, EventArgs e)
        {

        }
    }

The above figure clearly shows that the authorrepository instance has been successfully injected at runtime.

In the. Net framework 4.7.2 framework above, finally willDependency injection mechanismBrought into ASP. Net web forms, we need to understand that Microsoft’s unity package is a lightweight dependency injection container, which can be used on pages, controls, handlers and modules. Using dependency injection in ASP. Net web forms can easily create objects, and then obtain dependencies at runtime, which can make it easy for you to build flexible and loose applications.

More wonderful, welcome to subscribe

Translation link:https://www.infoworld.com/article/3397003/how-to-use-dependency-injection-in-aspnet-web-forms.html