1.首先使用nuget安装Autofac.Extras.CommonServiceLocator和autofac
为什么使用nuget,因为两个包会有很多依赖的包需要下载,为了不必要的麻烦,请使用nuget安装需要的包
2.创建需要的注入的类,接口和接口实现
public interface ISayAble
{
void SayHello();
}
public class Say:ISayAble
{
public void SayHello()
{
Console.WriteLine("老子就不是人!");
}
}
public Person(ISayAble say)
{
say.SayHello();
}
现在需要将say以参数的形式注入到Person中,再针对ServiceLocator做一些封装
public static T GetService<T>()
{
return ServiceLocator.Current.GetInstance<T>();
}
public static void SetService(IContainer container)
{
ServiceLocator.SetLocatorProvider(() => new AutofacServiceLocator(container));
}
使用autofac加载程序,我需要加载的程序集名字是Core.dll,所以
public static void App_Start()
{
var builder = new ContainerBuilder();
//module注册
Assembly[] asms = new Assembly[]
{
Assembly.LoadFrom("Core.dll")
};
builder.RegisterAssemblyTypes(asms)
.Where(t => !t.IsAbstract)
.PropertiesAutowired()
.AsImplementedInterfaces();
IContainer container = builder.Build();
ServiceResposity.SetService(container);
}
当然也可以不用关心dll的名字,直接一股脑全部加载进来,这里不做详解
准备工作做完了,接下来做一些分析,autofac在MVC中如果我没有记错的话,是重写了Controller的调用方法,那这里不是MVC,没有所谓的
调用方法怎么办呢?不要忘了工厂模式,不一定要去直接调用需要注入的方法,我们可以写个工厂来帮我们调用不就好了,
我只是很简单实现了一下这个工厂,代码如下:
public class Genericresposity<T>
{
private ISayAble say = ServiceResposity.GetService<ISayAble>();
//构造函数
public void CreateClass()
{
Type type = typeof(T);
ConstructorInfo info = type.GetConstructor(new[] { typeof(ISayAble) });
info.Invoke(new[] { say });
}
}
当然很乱,我只是很简单写了一下,大概意思就是,我们通过这个resposity去调用我们的Person就可以实现构造函数的注入,那么,其他的一些注入形式是不是都可以这样子做呢,
这个工厂还起到一个作用就是管理我们的实例
调用示例如下:
public class Genericresposity<T>
{
private ISayAble say = ServiceResposity.GetService<ISayAble>();
//构造函数
public void CreateClass()
{
Type type = typeof(T);
ConstructorInfo info = type.GetConstructor(new[] { typeof(ISayAble) });
info.Invoke(new[] { say });
}
}