1.概要
要实现批量注册的时候,也可以使用程序集的方式来注册。
2.代码
2.1 主函数
using Autofac;
using ClassLibrary1.IF;
using System;
using System.Reflection;
namespace AutoFac程序集注册
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("AutoFac程序集注册");
Assembly assembly = Assembly.LoadFrom("ClassLibrary1.dll");
var builder = new ContainerBuilder();
builder.RegisterAssemblyTypes(assembly)//程序集内所有具象类
.Where(c => c.Name.StartsWith("Class"))
.PublicOnly()//只要public访问权限的
.Where(cc => cc.IsClass)//只要class型(主要为了排除值和interface类型)
.AsImplementedInterfaces();//自动以其实现的所有接口类型暴露(包括IDisposable接口)
var container = builder.Build();
Interface1 interface1 = container.Resolve<Interface1>();
interface1.fun(1);
Interface2 interface2 = container.Resolve<Interface2>();
int ret = interface2.fun();
Console.WriteLine(ret);
Console.ReadKey();
}
}
}
2.2 接口
namespace ClassLibrary1.IF
{
public interface Interface1
{
void fun(int i);
}
}
namespace ClassLibrary1.IF
{
public interface Interface2
{
int fun();
}
}
2.3 类
using ClassLibrary1.IF;
using System;
namespace ClassLibrary1
{
public class Class1 : Interface1
{
public void fun(int i)
{
Console.WriteLine(i);
}
}
}
using ClassLibrary1.IF;
namespace ClassLibrary1
{
public class Class2 : Interface2
{
public int fun()
{
return 1;
}
}
}
3.运行效果
AutoFac程序集注册
1
1