AUTOFAC is an IOC framework, compared to spring.net,unity,castle and so on framework, it is very lightweight and performance is very high, the following small section to introduce the use of dependency injection framework AUTOFAC.
Below is the code to share with you the use of the dependency injection framework AUTOFAC, as follows:
AUTOFAC is an IOC framework that, compared to other IOC frameworks, such as Spring.net,unity,castle, is also very lightweight and very high in performance.
1) Decompression of its compression package, mainly see Autofac.dll,autofac.configuration.dll, which is also the focus of this article on the use of AUTOFAC class library.
2) Create a console project and reference the above DLL files. Create a database operator interface IDatabase.cs:
<summary>///Database operate interface///</summary>public interface idatabase{string Name {get;} void Select (String commandtext), void Insert (string commandtext), void Update (string commandtext), void Delete (string CommandText);}
Here are four ways to manipulate crud.
3) Create two types of database operation classes, SqlDatabase.cs and OracleDatabase.cs:
public class Sqldatabase:idatabase {public string Name { get {return ' SQL Server ';} } public void Select (string commandtext) { Console.WriteLine (string. Format ("' {0} ' is a query for SQL in {1}!", CommandText, Name)); } public void Insert (string commandtext) { Console.WriteLine (string. Format ("' {0} ' is a inserts SQL in {1}!", CommandText, Name)); } public void Update (string commandtext) { Console.WriteLine (string. Format ("' {0} ' is a update for SQL in {1}!", CommandText, Name)); } public void Delete (string commandtext) { Console.WriteLine (string. Format ("' {0} ' is a delete sql in {1}!", CommandText, Name));
And
public class Oracledatabase:idatabase {public string Name { get {return ' Oracle ';} } public void Select (string commandtext) { Console.WriteLine (string. Format ("' {0} ' is a query for SQL in {1}!", CommandText, Name)); } public void Insert (string commandtext) { Console.WriteLine (string. Format ("' {0} ' is a inserts SQL in {1}!", CommandText, Name)); } public void Update (string commandtext) { Console.WriteLine (string. Format ("' {0} ' is a update for SQL in {1}!", CommandText, Name)); } public void Delete (string commandtext) { Console.WriteLine (string. Format ("' {0} ' is a delete sql in {1}!", CommandText, Name)); } }
4) Next create a database manager DatabaseManager.cs:
public class Databasemanager { idatabase _database; Public Databasemanager (idatabase database) { _database = database; } public void Search (string commandtext) { _database. Select (commandtext); } public void Add (string commandtext) { _database. Insert (commandtext); } public void Save (string commandtext) { _database. Update (commandtext); } public void Remove (string commandtext) { _database. Delete (commandtext);} }
5) In the console, write the following test procedure:
var builder = new Containerbuilder (); Builder. Registertype<databasemanager> (); Builder. Registertype<sqldatabase> (). As<idatabase> (); using (var container = Builder. Build ()) {var manager = container. Resolve<databasemanager> (); Manager. Search ("SELECT * FORM USER"); }
Operation Result:
Analysis:
Here the Databasemanager is registered through the Containerbuilder method Registertype, and the registered type can resolve your Databasemanager instance in the corresponding container.
Copy CodeThe code is as follows: Builder. Registertype<sqldatabase> (). As<idatabase> ();
Using as allows the Databasemanager class to rely on the appropriate interface of the injected type through the constructor.
The build () method generates a corresponding container instance so that it can resolve to the registered type instance through resolve.
Similarly, if you modify the database type to register as:
Copy CodeThe code is as follows: Builder. Registertype<oracledatabase> (). As<idatabase> ();
Operation Result:
6) Obviously the above program, SQLDatabase or oracledatabase has been exposed to the client program, and now I would like to choose this type of file configuration for reading.
The AUTOFAC comes with a Autofac.Configuration.dll very convenient to configure the type, avoiding the recompilation of the program.
Modify App. Config:
Copy CodeThe code is as follows:< configuration> <configSections> <section name= "AUTOFAC" type= "Autofac.Configuration.SectionHa Ndler, autofac.configuration "/> </configSections> <autofac defaultassembly=" Autofacdemo "> <compo nents> <component type= "autofacdemo.sqldatabase, Autofacdemo" service= "Autofacdemo.idatabase"/> </c Omponents> </autofac> </configuration>
The component is processed through the Autofac.Configuration.SectionHandler configuration node.
The corresponding client program is changed to:
Copy CodeThe code is as follows: var builder = new Containerbuilder (); Builder. Registertype<databasemanager> (); Builder. Registermodule (New Configurationsettingsreader ("AUTOFAC")); using (var container = Builder. Build ()) {var manager = container. Resolve<databasemanager> (); Manager. Search ("SELECT * FORM USER"); }
Operation Result:
7) There is another way to register through the Register method:
var builder = new Containerbuilder ();//builder. Registertype<databasemanager> (); builder. Registermodule (New Configurationsettingsreader ("AUTOFAC")); builder. Register (c = new Databasemanager (c.resolve<idatabase> ())); using (var container = Builder. Build ()) { var manager = container. Resolve<databasemanager> (); Manager. Search ("SELECT * FORM USER");}
The results are the same.
8) Now I want to use a user class to control operation permissions, such as adding and deleting permissions, create a user class:
<summary>//ID identity Interface//</summary> public Interface identity { int Id {get; set;}} public class User:identity {public int Id {get; set;} public string Name {get; set;}}
To modify the DatabaseManager.cs code:
public class Databasemanager {idatabase _database; User _user; Public Databasemanager (Idatabase database): This (database, NULL) {} public Databasemanager (Idatabase database, User User) {_database = database; _user = user; }//<summary>//Check Authority//</summary>//<returns></returns> public bool is Authority () {bool result = _user! = null && _user. Id = = 1 && _user. Name = = "Leepy"? True:false; if (!result) Console.WriteLine ("Not authority!"); return result; } public void Search (string commandtext) {_database. Select (CommandText); } public void Add (string commandtext) {if (isauthority ()) _database. Insert (CommandText); public void Save (string commandtext) {if (isauthority ()) _database. Update (CommandText); } public void Remove (string commandtext) {if (isauthority ()) _database. Delete (CommandText); } }
A parameter user was added to the constructor, and Add,save,remove added permission to judge.
To modify the client program:
User User = new User {Id = 1, Name = "Leepy"}; var builder = new Containerbuilder (); Builder. Registermodule (New Configurationsettingsreader ("AUTOFAC")); Builder. RegisterInstance (user). As<user> (); Builder. Register (c = new Databasemanager (c.resolve<idatabase> (), c.resolve<user> ())); using (var container = Builder. Build ()) { var manager = container. Resolve<databasemanager> (); Manager. ADD ("INSERT into USER ...");}
Operation Result:
Analysis:
Copy CodeThe code is as follows: Builder. RegisterInstance (user). As<user> (); Register the User instance. Builder. Register (c + = new Databasemanager (c.resolve<idatabase> (), c.resolve<user> ())); Registration by LAMPDA expression
Databasemanager instance.
If I change the user's property value here:
Copy CodeThe code is as follows: User user = new User {Id = 2, Name = "Zhangsan"};
Operation Result:
Indicates that the user does not have permission to operate.
The above is the whole content of this article, I hope you like.
Analysis on the use of dependency injection frame AUTOFAC