依赖注入容器有很多插件,我用过Unity和Autofac,这两个插件给我最明显的感觉就是Autofac很快,非常的快,毕竟是第三方开发的,而Unity相对而言性能比较稳定
下面附上Autofac自动注入代码:(IDependency接口表示要注入的接口必须要继承它,WEB中必须要添加接口类库和接口实现类库,否则会注入失败),其实原理就是反射
using System.Linq;
using System.Reflection;
using System.Web.Compilation;
using System.Web.Mvc;
using Autofac;
using Autofac.Integration.Mvc;
using Framework.Core; namespace MsSystem.Web
{
/// <summary>
/// Autofac依赖注入配置
/// </summary>
public class AutofacConfig
{
/// <summary>
/// 初始化
/// </summary>
public static void Initialise()
{
var builder = RegisterService();
DependencyResolver.SetResolver(new AutofacDependencyResolver(builder.Build()));
} /// <summary>
/// 注入实现
/// </summary>
/// <returns></returns>
private static ContainerBuilder RegisterService()
{
var builder = new ContainerBuilder(); var baseType = typeof(IDependency); //扫描IService和Service相关的程序集 var assemblys = BuildManager.GetReferencedAssemblies().Cast<Assembly>()
.Where(m => m.FullName.Contains("MsGPM")).ToList(); builder.RegisterControllers(assemblys.ToArray()); //自动注入
builder.RegisterAssemblyTypes(assemblys.ToArray())
.Where(t => baseType.IsAssignableFrom(t) && t != baseType)
.AsImplementedInterfaces().InstancePerLifetimeScope();
return builder;
}
}
}
在Global Application_Start 中添加AutofacConfig.Initialise()方法即可。
使用的话,我一般都是构造函数注入方式