Net7 使用 Autofac 依赖注入

示例项目目录

 

第一步.、添加 Nuget 包引用

Autofac

Autofac.Extensions.DependencyInjection

AutoMapper

AutoMapper.Extensions.Microsoft.DependencyInjection

 第二步、创建接口(IService) 、 实现类(Service)、实体类(Model)

接口,IClass1Service

public interface IClass1Service
{
    public void Hello(Class1Model model);
}

 实现类,IClass1Service

public class Class1Service: IClass1Service
{
    public void Hello(Class1Model model)
    {

    }
}

 实体类,Class1Model

public class Class1Model
{
    public int Id { set; get; }
    public string? Name { set; get; }
    public DateTime CreateTime { set; get; } = DateTime.Now;
}

 

 第三步、依赖注入,注意:接口类使用 Service 结尾,MenuService.cs

//Autofac注入,工厂模式
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
builder.Host.ConfigureContainer<ContainerBuilder>(builder =>
{
    //自动注册服务及允许AOP拦截
    Assembly service = Assembly.Load("Micro.Bpm.Services");
    Assembly iservice = Assembly.Load("Micro.Bpm.IServices");
    //类名以service结尾,且类型不能是抽象的
    builder.RegisterAssemblyTypes(service, iservice)
        .Where(t => (t.FullName != null && t.FullName.EndsWith("Service")) && !t.IsAbstract)
        .AsImplementedInterfaces()
        //生命周期
        .InstancePerDependency();
});

第四步、控制器使用

private readonly IClass1Service _class1;
public ValuesController(IClass1Service class1)
{
    _class1 = class1;
}

 

第五步、配置类型转换,AutoMapper.Extensions.Microsoft.DependencyInjection,NuGet包

//扫描Profile文件
builder.Services.AddAutoMapper(s => s.AddProfile(typeof(AutoMapperProfile)));
builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

 第六步、创建 ViewModel 和 实现 Profile 类

public class Class1EditDto
{
    public int Id { set; get; }
    public string? Name { set; get; }
}

 

namespace Micro.Bpm.Profiles
{
    public class AutoMapperProfile : Profile
    {
        /// <summary>
        /// 实体映射
        /// </summary>
        public AutoMapperProfile()
        {
            #region 菜单主表
            CreateMap<Class1Model, Class1EditDto>();
            //DTO映射到源数据
            CreateMap<Class1EditDto, Class1Model>();
            #endregion
        }
    }
}

 

 第七步、实体转换示例

private readonly IMapper _mapper;
private readonly IClass1Service _class1;
public ValuesController(IMapper mapper, IClass1Service class1)
{
    _mapper = mapper;
    _class1 = class1;
}

 

[HttpPost]
public void Post([FromBody] Class1EditDto value)
{
    //Class1EditDto 转为 Class1Model
    var model = _mapper.Map<Class1Model>(value);
    _class1.Hello(model);
}

 

posted @ 2023-11-21 01:30  microsoft-zhcn  阅读(156)  评论(0编辑  收藏  举报