C# MEF“松耦合” 依赖注入 ComponentModel
面向借口的编程微软有一个很好的组件开发框架。 System.ComponentModel.Composition。
记一个小例子:
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
1.定义接口
public interface IUserAction
{
List<T> Test();
}
2.定义实现类:
[Export("StudentAction", typeof(IUserAction))]
public class StudentAction : IUserAction
{
public List<T> Test()
{
return new List<T>();
}
}
3.注册Dll
public static CompositionContainer DependencyRegistInstance
{
get
{
return (CompositionContainer)System.Web.HttpContext.Current.Application["AllDependency"];
}
}
(a)根据具体的一个类,注册对应的Assembly
public void Init()
{
AggregateCatalog catalog = new AggregateCatalog();
catalog.Catalogs.Add(new AssemblyCatalog(typeof(UserAction).Assembly));
CompositionContainer container = new CompositionContainer(catalog);
System.Web.HttpContext.Current.Application["AllDependency"] = container;
}
(b)读取外部路径注册部件
public void Init()
{
DirectoryCatalog catalog = new DirectoryCatalog ("using");
CompositionContainer container = new CompositionContainer(catalog);
System.Web.HttpContext.Current.Application["AllDependency"] = container;
}
4.在调用类的时候把当前类邦定到主件对象上
var container = DependencyRegist.DependencyRegist.DependencyRegistInstance;
container.ComposeParts(this);
5.直接调用接口
[Import("StudentAction")]
private IUserAction user;
public ActionResult Index()
{
var list = user.Test();
return View(list);
}