. Net reflection and dependency Injection

Source: Internet
Author: User

Deep understanding of dependency injection: http://kb.cnblogs.com/page/45266/

. Net reflection and dependency Injection

Interface reflection:

Interface Layer: the interface is defined as the Dal layer.

Interface idal

Use reflection technology (reflection) to create interface instances required to lock idal in factory Mode

Example:

String Path = "Dal ";
Private Dal. idal createidal (string Str)
{
String classname = path + ". Dal" + STR;
Return (DAL. idal) system. reflection. Assembly. Load (PATH). createinstance (classname );
}

Public String getstr (string Str)
{
Idal Dal = createidal (STR );
Return Dal. getstring ();
}

Dependency injection:

According to the requirement mode of dependency Injection

Interface: IA

A: IA

Interface: IB

B: IB

Implement in A: IA

Instantiation of IB (using reflection technology)

In the main program, you can implement the IA instance and call the IB member function.

Example:

Define the class library idal

IA. CS

Using system;

Namespace idal
{
Public interface IA
{
String show ();
}
}
Ib. CS

Using system;

Namespace idal
{
Public interface IB
{
String getcode ();
}
}
A. CS

Using system;

Namespace idal
{
Public Class A: IA
{
Private IB = factory. createib ();

Public String show ()
{
Return Ib. getcode ();
}
}
}
B. CS

Using system;

Namespace idal
{
Public Class B: IB
{
Public String getcode ()
{
Return "B ";
}
}
}

Factory. CS // interface factory required for reflection

Using system;

Namespace idal
{
Public class factory
{
Static string Path = "idal ";
Static string classname = "";

Public static idal. Ia createia ()
{
Classname = path + ". ";
Return (idal. Ia) system. reflection. Assembly. Load (PATH). createinstance (classname );
}

Public static idal. IB createib ()
{
Classname = path + ". B ";
Return (idal. Ib) system. reflection. Assembly. Load (PATH). createinstance (classname );
}
}
}

Call a function

Ia = factory. createia ();
IA. Show ();

From: http://blog.csdn.net/angelzjk/article/details/5620324

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.