[Selfless sharing: ASP. net core Project Practice (chapter 2)] add EF context objects, add interfaces, implementation classes, and ubiquitous dependency injection (DI ).

Source: Internet
Author: User

[Selfless sharing: ASP. net core Project Practice (chapter 2)] add EF context objects, add interfaces, implementation classes, and ubiquitous dependency injection (DI ).
Directory Index

 

[Selfless sharing: ASP. net core project practice] Directory Indexing

 

Introduction

 

In the previous chapter, we introduced how to install and create controllers and views. In this chapter, we create a data model and Add Interfaces and implementation classes.

 

 

Add an EF context object

 

According to our previous habits, we still need to create several folders.

Commons: stores help classes

Domians: Data Model

Services: interfaces and implementation classes



We add a class library Domain under the Domains folder.

 


 

Create a new class ApplicationDbContext to inherit DbContext

1 using Microsoft.EntityFrameworkCore;
 2 
 3 namespace Domain
 4 {
 5     public class ApplicationDbContext : DbContext
 6     {
 7         public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
 8             : base(options)
 9         {
10         }
11 
12         protected override void OnModelCreating(ModelBuilder builder)
13         {
14             base.OnModelCreating(builder);
15         }
16     }
17 }


Note:

DbContext must reference Microsoft. EntityFrameworkCore

Method 1: Select DbContext and add Microsoft. EntityFrameworkCore reference by pressing Ctrl +.

Method 2: Add Microsoft. EntityFrameworkCore reference to project. json of the Domain class library

 

Then, open \ src \ Startu. cs to modify the ConfigureServices (IServiceCollection services) method, and add support for EF (highlighted in yellow ):


1     // This method gets called by the runtime. Use this method to add services to the container.
 2         public void ConfigureServices(IServiceCollection services)
 3         {
 4             // Add framework services.
 5             services.AddApplicationInsightsTelemetry(Configuration);
 6 
 7             services.AddDbContext<ApplicationDbContext>(options =>options.UseSqlServer(Configuration.GetConnectionString("SqlServerConnection")));
 8 
 9             services.AddMvc();
10 
11         }

 

The above SqlServerConnection is our database connection string, which is configured in the \ src \ appsettings. json file (this name reminds us of appsetting. config ):


 

 

In this way, we have actually completed the operation, but we will use it later. We do not operate the data currently.

 

Add Interfaces and implementation classes

 

Let's add an interface and implementation class. Let's take a look at the dependency injection of Asp.net Core.

Add a class library Service under the Services folder


 

 

In the Service class library, we create three folders:

IDao: stores basic operations

IService: stores interface files

ServiceImp: storage implementation class

IDao, we don't care about it first. We will use IRepositorycs and Repositorycs (DDD drive design) later. We mainly add an interface and implementation class. To better classify interfaces and implement classes, we create a folder SysManage under the IService and ServiceImp folders to store system management interfaces.

 

Create an IUserManage interface under \ IService \ SysManage \.

 

1 namespace Service.IService
2 {
3     public interface IUserManage
4 {
5         /// <summary>
6 / / / test interface
7         /// </summary>
8         /// <returns></returns>
9         string Test();
10}
11}

 

 

Create an implementation class UserManage under \ ServiceImp \ SysManage \.

1 namespace Service.ServiceImp
2 {
3     public class UserManage : IService.IUserManage
4 {
5         public string Test()
6 {
7 return "I implemented the interface method test";
8}
9}
10}

 

 

Modify the ConfigureServices (IServiceCollection services) method of \ src \ Startu. cs to implement injection (highlighted in yellow ):

1 // This method gets called by the runtime. Use this method to add services to the container.
 2         public void ConfigureServices(IServiceCollection services)
 3         {
 4             // Add framework services.
 5             services.AddApplicationInsightsTelemetry(Configuration);
 6 
 7             services.AddDbContext<ApplicationDbContext>(options =>options.UseSqlServer(Configuration.GetConnectionString("SqlServerConnection")));
 8 
 9             services.AddMvc();
10 
11             // Add application services.       
12             services.AddTransient<Service.IService.IUserManage, Service.ServiceImp.UserManage>();
13         }

 

Note:


 

 

Call Interface

 

There are three injection methods: constructor injection, property injection, and method injection. In the [selfless sharing: Getting started to mastering ASP. net mvc] series, most of us use Attribute injection. Today we use constructor injection:

We declare the interface in HomeController

Private readonly IUserManage _ UserManage;

Add the following to the Controller constructor:

Public HomeController (IUserManage UserManage)
{
_ UserManage = UserManage;
}

The dependency injection framework automatically finds the instance of the IUserManage implementation class and assigns it to the constructor.

 

Let's test in the About View:

Public IActionResult About ()
{
ViewData ["Message"] = _ UserManage. Test ();

Return View ();
}

 

Ctrl + F5 run:


 

Indicates that the injection is successful! (In Asp.net Core, we can directly save and refresh the page after modifying the code. We don't need to re-compile and generate it as before. This is awesome .)

 

Three injection methods:

 

Constructor Injection

The constructor injection injects the dependent objects into the created objects by using parameters in the constructor. As shown in the following code snippet, Foo's dependence on Bar is reflected in the read-only attribute Bar, and its initialization implementation is in the constructor, the specific attribute values are provided by the parameters passed in by the constructor. Before the DI container creates a Foo object by calling the constructor, it needs to create and initialize the parameter object based on the currently registered type Matching Relationship and other related injection information.

 

 1: public class Foo
   2: {
   3:     public IBar Bar{get; private set;}
   4:     public Foo(IBar bar)
   5:     {
   6:         this.Bar = bar;
   7:     }
   8: }

 

In addition, constructor injection is also reflected in the selection of constructor. As shown in the following code snippet, the Foo class defines two constructors. The DI container should select a suitable constructor before creating the Foo object. As for how to select the target constructor, different DI containers may have different policies. For example, you can select multiple or least parameters, alternatively, you can mark a related feature on the target constructor as follows (we have labeled an InjectionAttribute feature on the first constructor ).

 

 1: public class Foo
   2: {
   3:     public IBar Bar{get; private set;}
   4:     public IBaz Baz {get; private set;}
   5:  
   6:     [Injection]
   7:     public Foo(IBar bar)
   8:     {
   9:         this.Bar = bar;
  10:     }
  11:  
  12:     public Foo(IBar bar, IBaz):this(bar)
  13:     {
  14:         this.Baz = baz;
  15:     }
  16: }

 

 

Property Injection

If dependency is directly reflected as an attribute of the class and this attribute is not read-only, we can enable the DI container to automatically assign values to it after the object is created to achieve automatic dependency injection. In general, when defining this type, we need to explicitly mark this property as a Dependency Property that needs to be automatically injected to distinguish it from other common properties of this type. As shown in the following code snippet, the Foo class defines two public attributes Bar and Baz that can be read and written. We set the attribute Baz as the dependency attribute of automatic injection by marking the InjectionAttribute feature. For the Foo object provided by DI container, its Baz attribute will be automatically initialized.

  1: public class Foo
   2: {
   3:     public IBar Bar{get; set;}
   4:  
   5:     [Injection]
   6:     public IBaz Baz {get; set;}
   7: }

 

Method Injection

Fields or attributes that reflect dependencies can be initialized in the form of methods. As shown in the following code snippet, Foo's dependence on Bar is reflected in the read-only attribute. The initialization implementation of this attribute is in the Initialize method. The specific attribute values are provided by the parameters passed in by the constructor. We also mark this method as an injection method by marking the feature (InjectionAttribute. After the DI container creates a Foo object by calling the constructor, it automatically calls the Initialize method to assign values to the read-only attribute Bar. Before calling this method, DI container initializes the parameters of this method based on the pre-registered type ing and other related injection information.

1: public class Foo 2: {
   3:     public IBar Bar{get; private set;}
   4:  
   5:     [Injection]
   6:     public Initialize(IBar bar)
   7:     {
   8:         this.Bar = bar;
   9:     }
  10: }

 

 

I hope to study Asp.net Core with you.

At the beginning, there was a limited level of contact, and many things were self-understanding and reading the information of the great gods on the Internet. If there is something wrong or incomprehensible, I hope you can correct it!

Although Asp.net Core is very popular now, many materials on the Internet are copied in the previous article, so I have not solved many problems for the time being. I hope you can help me together!

 

Original article reprinted please respect labor results http://yuangang.cnblogs.com

 


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.