autoFac 程序集注册 简单试验

本文介绍了如何使用Autofac框架在C#程序集中批量注册接口和类,通过`ContainerBuilder`动态加载`ClassLibrary1.dll`中的符合特定条件的类,并以其实现的接口进行依赖注入。
摘要由CSDN通过智能技术生成

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值