CS. dynamically load DLL. dynamically generate. Run code. BS. AutoFac management implementation class, dll. bs. autofac

Source: Internet
Author: User

CS. dynamically load DLL. dynamically generate. Run code. BS. AutoFac management implementation class, dll. bs. autofac

Take League of legends as an example. load .... xxxx. dll. generally, it is the loading subsystem. for example, the equipment system. hero system. in actual development, many projects are very large. it is divided into independent sub-solution development. it needs to be loaded back later. generally, dynamic code loading is used.

... The image cannot be uploaded at this time point.

 

Father // parent solution. login page and Load. Load the sub-solution Dll page

 

Father1 // The class library under the parent solution has a common parent class. All Sub-solutions will load such libraries.

 

Son // sub-solution. Equipment System. Hero System

------------------------------------

The idea is that the Father solution loads all Son sub-solutions and uses the Father1 solution to generate associations.

 

Father1 may be an interface. Son implementation. But Son sets up a new solution independently of Father.

 

Father1:

 

Public interface Class1
{
Void run (string message );
}

 

Son:

 

Public class Class1: ClassLibrary1.Class1
{
Public void run (string message)
{
Console. WriteLine (message );
}
}

 

Father:

 

Var filepath = @ "C: \ Users \ Administrator \ Desktop \ DEV_DLL \ ConsoleApplication1 \ ClassLibrary2 \ bin \ Debug \ ClassLibrary2.dll ";
Var ass = System. Reflection. Assembly. LoadFrom (filepath );
Foreach (var item in ass. GetTypes ())
{
If (item. GetInterface ("Class1 ")! = Null)
{
Var classlibrary = (ClassLibrary1.Class1) Activator. CreateInstance (item );
Classlibrary. run ("hello ");
}

}

 

Dynamic Loading is completed because it is a dynamic dll. You may need to write and execute code dynamically.

For example, string a = "string B = '1 '";

Then make B take effect

 



CSharpCodeProvider objCSharpCodePrivoder = new CSharpCodeProvider ();


ICodeCompiler objICodeCompiler = objCSharpCodePrivoder. CreateCompiler ();


CompilerParameters objCompilerParameters = new CompilerParameters ();
ObjCompilerParameters. ReferencedAssemblies. Add ("System. dll ");
ObjCompilerParameters. GenerateExecutable = false;
ObjCompilerParameters. GenerateInMemory = true;

// 4. CompilerResults
CompilerResults cr = objICodeCompiler. CompileAssemblyFromSource (objCompilerParameters, GenerateCode ());

If (cr. Errors. HasErrors)
{
Console. WriteLine ("Compilation error :");
Foreach (CompilerError err in cr. Errors)
{
Console. WriteLine (err. ErrorText );
}
}
Else
{
// Call the HelloWorld instance through reflection
Assembly objAssembly = cr. CompiledAssembly;
Object objHelloWorld = objAssembly. CreateInstance ("DynamicCodeGenerate. HelloWorld ");
MethodInfo objMI = objHelloWorld. GetType (). GetMethod ("OutPut ");

Console. WriteLine (objMI. Invoke (objHelloWorld, null ));
}

 

Static string GenerateCode ()
{
StringBuilder sb = new StringBuilder ();
Sb. Append ("using System ;");
Sb. Append (Environment. NewLine );
Sb. Append ("namespace DynamicCodeGenerate ");
Sb. Append (Environment. NewLine );
Sb. Append ("{");
Sb. Append (Environment. NewLine );
Sb. Append ("public class HelloWorld ");
Sb. Append (Environment. NewLine );
Sb. Append ("{");
Sb. Append (Environment. NewLine );
Sb. Append ("public string OutPut ()");
Sb. Append (Environment. NewLine );
Sb. Append ("{");
Sb. Append (Environment. NewLine );
Sb. Append ("return \" Hello world! \";");
Sb. Append (Environment. NewLine );
Sb. Append ("}");
Sb. Append (Environment. NewLine );
Sb. Append ("}");
Sb. Append (Environment. NewLine );
Sb. Append ("}");

String code = sb. ToString ();
Console. WriteLine (code );
Console. WriteLine ();

Return code;
}

 

// The above completes dynamic coding and Execution Code

 

AutoFac is the most lightweight and fastest IOC framework and is recommended by Microsoft.

Dependency injection. Dependency implementation class injection container

Control inversion. Separate implementation classes in containers

Core Idea: interface-oriented programming rather than implementation class

 

There are two injection methods for AutoFac. One is dependency injection. The effect is that an interface corresponds to an implementation class. Manual Injection

 

One is dependent on query. Use the IDependency interface to implement automatic class injection.

 

// Manual Injection

Var builder = new ContainerBuilder ();
SetupResolveRules (builder );
Builder. RegisterControllers (Assembly. GetExecutingAssembly ());
Var container = builder. Build ();
DependencyResolver. SetResolver (new AutofacDependencyResolver (container ));

AreaRegistration. RegisterAllAreas ();
WebApiConfig. Register (GlobalConfiguration. Configuration );
FilterConfig. RegisterGlobalFilters (GlobalFilters. Filters );
RouteConfig. RegisterRoutes (RouteTable. Routes );
BundleConfig. RegisterBundles (BundleTable. Bundles );
AuthConfig. RegisterAuth ();

Private void SetupResolveRules (ContainerBuilder builder)
{
Builder. RegisterType <GradeService1> (). As <IGradeService1> ();
Builder. RegisterType <GradeService> (). As <IGradeService> ();

// Explicit type registration
}

 

Create the IOC container ContainerBuilder in Global. asax. Inject the interface. IOC into the constructor to automatically inject the implementation class.

 

Public HomeController (IGradeService1 ser, IGradeService ser1)
{
Ser1 = ser;
Ser = ser1;
}

Public ActionResult Index ()
{
Var a = Ser. GetName ();
Var a1 = Ser1.GetName ();
Return View ();
}

 

// Automatic Registration

 

AreaRegistration. RegisterAllAreas ();

Var builder = RegisterService ();

DependencyResolver. SetResolver (new AutofacDependencyResolver (builder. Build ()));
WebApiConfig. Register (GlobalConfiguration. Configuration );
FilterConfig. RegisterGlobalFilters (GlobalFilters. Filters );
RouteConfig. RegisterRoutes (RouteTable. Routes );
BundleConfig. RegisterBundles (BundleTable. Bundles );
AuthConfig. RegisterAuth ();

// Depends on the IDependency interface for Automatic Registration

 

Public ContainerBuilder RegisterService ()
{
Var builder = new ContainerBuilder ();

Var baseType = typeof (IDependency );
Var assemblys = AppDomain. CurrentDomain. GetAssemblies (). ToList ();
Var AllServices = assemblys
. Selecttypes (s => s. GetTypes ())
. Where (p => baseType. IsAssignableFrom (p) & p! = BaseType );

Builder. RegisterControllers (assemblys. ToArray ());

Builder. RegisterAssemblyTypes (assemblys. ToArray ())
. Where (t => baseType. IsAssignableFrom (t) & t! = BaseType)
. AsImplementedInterfaces (). instanceperlifetimesloud ();
Return builder;
}

// Use the lambda deduction type to find the implementation class

 

// Create an empty IDependency Interface

Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Using System. Threading. Tasks;

Namespace WebApplication1.Models
{
Public interface IDependency
{
}
}

 

Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Using System. Threading. Tasks;
Using WebApplication1.Models;

Namespace WebApplication1.Controllers
{
Public interface IGradeService: IDependency
{
String GetName ();

}
Public interface IGradeService1: IDependency
{
String GetName ();

}
}

 

As long as the interface inherits IDependency. AutoFac will automatically find the implementation class and inject the implementation class when constructing the function Injection Interface.

 

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.