大多数时候,我们都是以下面这种方式用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
{
}
}