一、官方文档
https://autofaccn.readthedocs.io/zh/latest/index.html
二、新建.net core 控制台程序
三、注册类型,示例一
1、新建接口 IPerson
public interface IPerson { void Introduction(); }
2、实现接口,新建类Worker
public class Worker : IPerson { public void Introduction() { Console.WriteLine("I am a worker"); } }
3、新建类RegisterConsoles并注册组件
public class RegisterConsoles {/// <summary> /// 通过类型注册来注入 /// </summary> public static void TypeRun() { var builder = new ContainerBuilder(); builder.RegisterType<Worker>().As<IPerson>(); var container = builder.Build(); var serviceProvider = new AutofacServiceProvider(container); var person = serviceProvider.GetService<IPerson>(); person.Introduction(); Console.ReadKey(); } }
4、执行程序
class Program { static void Main(string[] args) { Console.WriteLine("autofac demo"); RegisterConsoles.TypeRun(); } }
输出如图信息:
四、如果有很多组件需要注册呢,难道每一个都要写一行代码吗,显然是不合适的。因此可以通过程序集反射来注册
示例二:
1、新建接口
/// <summary> /// 继承此接口则自动注入 /// </summary> public interface IDependency { }
2、添加自动注入的逻辑,新建类AutoRegister
public class AutoRegister { /// <summary> /// 自动注入 /// </summary> /// <returns></returns> public AutofacServiceProvider Build() { var builder = new ContainerBuilder(); Type dependencyType = typeof(IDependency); var assemblys = AppDomain.CurrentDomain.GetAssemblies().ToArray(); builder.RegisterAssemblyTypes(assemblys) .Where(type => dependencyType.IsAssignableFrom(type) && !type.IsAbstract) .AsImplementedInterfaces().InstancePerLifetimeScope(); var container = builder.Build(); var serviceProvider = new AutofacServiceProvider(container); return serviceProvider; } }
3、新建类Teacher,实现接口IPerson,和IDependency
class Teacher : IPerson, IDependency { public void Introduction() { Console.WriteLine("I am a teacher"); } }
4、运行程序
static void Main(string[] args) { Console.WriteLine("autofac demo"); RegisterConsoles.AssemblyRun(); }
输出如下图:
参考
https://stackoverflow.com/questions/26957519/ef-core-mapping-entitytypeconfiguration