Autofac简单学习

学习地址:https://masuit.com/1192?kw=Autofac

强烈推荐勤快哥的小站https://masuit.com

资源多多

整体代码结构如下:

一、简单默认方式注入

1、IService

using System;
using System.Collections.Generic;
using System.Text;

namespace IService
{
    public interface IUserInfoService
    {
        string[] GetUsers();
    }
}

2、Service

using IService;
using System;
using System.Collections.Generic;
using System.Text;

namespace Service
{
    public class UserInfoService: IUserInfoService
    {
        public string[] GetUsers() {
            return new[] { "张三","李四"};
        }
    }
}

3、注入

namespace TestAutoFac
{
    public class AutofacModuleRegister : Autofac.Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            var basePath = AppContext.BaseDirectory;
            var servicesDllFile = Path.Combine(basePath, "Service.dll");
            var assemblysServices = Assembly.LoadFrom(servicesDllFile);
            //带有接口的带有接口层的服务注入
            builder.RegisterAssemblyTypes(assemblysServices)
                      .AsImplementedInterfaces()
                      .InstancePerDependency();
        }
    }
}

  

二、属性注入  

测试了下,跨项目好像不行,只能在同一个项目中测试了一下。

 接口和类实现与上面的代码一致。

关键点如下:

1、注入

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace TestAutoFac
{
    public class AutofacModuleRegister : Autofac.Module
    {
        protected override void Load(ContainerBuilder builder)
        {
                        //属性注入
            builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).AsImplementedInterfaces()
                .Where(t => t.Name.EndsWith("Controller") || t.Name.EndsWith("UserInfo"))
                .PropertiesAutowired().AsSelf().InstancePerDependency();
        }
    }
}

2、组件依赖

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            services.AddMvc().AddControllersAsServices();//这个加一下
        }

  

更具体的可以见

https://masuit.com/1435?kw=Autofac

原文地址:https://www.cnblogs.com/sailing92/p/14155319.html