AutoFac属性自动注入

大多数时候,我们都是以下面这种方式用Autofac来实现依赖注入:

// Create the builder with which components/services are registered.
 var builder = new ContainerBuilder();

 // Register all the dependencies
 builder.RegisterType<BookManager>().As<IBookManager>();
 builder.RegisterType<AuthorManager>().As<IAuthorManager>();
 builder.RegisterType<BookRatingManager>().As<IBookRatingManager>();
 builder.RegisterType<AuthorRatingManager>().As<IAuthorRatingManager>();

上面的写法,有如下问题:

开放封闭原则被违反,因为每一个时间开发人员都需要手动注册依赖项。
在代码合并过程中,开发人员会很好地错过某些行,这可能会导致问题的产生。
随着代码库的增长,会出现维护代码的问题。


以上问题,我们可以考虑使用属性(Attribute)来解决此问题:

1.编写如下代码

using System;

namespace JuCheap
{
    public class DependencyRegisterAttribute : Attribute
    {

    }
}

2.修改注入代码

// Create the builder with which components/services are registered.
 var builder = new ContainerBuilder();

// Resolve all the dependencies for the classes decorated with DependecyRegister
 builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies())
                         .Where(t => t.GetCustomAttribute<DependencyRegisterAttribute>() != null)
                         .AsImplementedInterfaces()
                         .InstancePerRequest();

3.在需要做依赖注入的代码上,加上DependencyRegisterAttribute

namespace JuCheap.Services
{
    [DependencyRegister]
    public class BookManager : IBookManager
    {

    }
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值