How to use Lamar in ASP. Net core

Time:2021-7-28

ASP. Net comes with a minimalist coreOut of the boxIn fact, you can also use third-party dependency injection containersDependency injection containerInstead of it, dependency injection is a design pattern that can effectively decouple objects and improve unit testing and maintainability. You can use itDependency injectionTo improve your code design, instead of new objects everywhere.

Lamar is a popular, efficient and modular IOC container. In this article, we will discuss how to use Lamar in ASP. Net core.

Why use Lamar to implement dependency injection

The earliest dependency injection container in the. Net world belongs toStructureMap, butStructureMapThe biggest disadvantage is the performance problem. The Lamar in this article is very lightweight and provides rich APIs to call. Lamar is very similar to structuremap. If you used to play with structuremap, it is very easy to switch to Lamar.

Installing Lamar

To use Lamar in ASP. Net core, you need to install the following two packages through nuget.

  • Lamar

  • Lamar.Microsoft.DependencyInjection

You can use the visual interfaceManage NuGet Packages

Or use the following command to install.

Install-Package Lamar 
Install-Package Lamar.Microsoft.DependencyInjection

Create idbmanager and dbmanager

First, create an idbmanager interface class for subsequent dependency injection. The code definition is as follows:

public interface IDBManager
    {
        void Initialize();
        bool Save(T obj);
    }

Next, define the dbmanager class and implement the interface idbmanager. The code definition is as follows:

public class DBManager: IDBManager
    {
        public void Initialize()
        {
            //Write some initialization code here
        }
        public bool Save(T obj)
        {
         //Write your code here
            return true;
        }
    }

Configuring Lamar

Lamar.Microsoft.DependencyInjectionThe package provides aUseLamar()Method can introduce Lamar into ASP. Net core infrastructure. The following code shows how to implement it.

public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).UseLamar().Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup();
                });
    }

Configure Lamar container

Next, you canConfigureServices()Method, and the code is as follows:

public void ConfigureServices(IServiceCollection services)
        {
            var container = new Container(x =>
            {
                x.AddTransient();
            });

            services.AddControllersWithViews();
        }

It is worth noting that Lamar has a strongautomatic assemblyAbility, which can search the constructor of request type and required type, and build the required instance. The following code shows how toConfigureContainer()Method to implement, here I put the method inStartupClass, the complete code is as follows:

public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var container = new Container(x =>
            {
                x.AddTransient();
            });

            services.AddControllersWithViews();
        }

        public void ConfigureContainer(ServiceRegistry services)
        {
            services.Scan(s =>
            {
                s.TheCallingAssembly();
                s.WithDefaultConventions();
            });
        }
    }

Inject dbmanager instance into controller

Next, you can obtain the dbmanager instance through dependency injection in the controller. The implementation code is as follows:

public class HomeController : Controller
    {
        private readonly ILogger _logger;
        private IDBManager _dbManager;

        public HomeController(ILogger logger, IDBManager dbManager)
        {
            _logger = logger;
            _dbManager = dbManager;
        }

        public IActionResult Index()
        {
            return View();
        }
    }

The dependency injection container of ASP. Net core is too weak in the IOC circle and needs to be expanded by a third party. Lamar is such an excellent IOC container and a good substitute for structuremap.

More exciting, welcome to subscribe

Translation link:https://www.infoworld.com/article/3339698/how-to-use-lamar-in-aspnet-core.html

Recommended Today

Implementation example of go operation etcd

etcdIt is an open-source, distributed key value pair data storage system, which provides shared configuration, service registration and discovery. This paper mainly introduces the installation and use of etcd. Etcdetcd introduction etcdIt is an open source and highly available distributed key value storage system developed with go language, which can be used to configure sharing […]