控制反转容器 【Autofac】 的使用

1. 注册组件

var builder = new ContainerBuilder();

// Register individual components
builder.RegisterInstance(new TaskRepository())
       .As<ITaskRepository>();
builder.RegisterType<TaskController>();
builder.Register(c => new LogManager(DateTime.Now))
       .As<ILogger>();

// Scan an assembly for components
builder.RegisterAssemblyTypes(myAssembly)
       .Where(t => t.Name.EndsWith("Repository"))
       .AsImplementedInterfaces();

var container = builder.Build();

 

2.依赖注入

public class TaskController
{
  private ITaskRepository _repository;
  private ILogger _logger;

  // Autofac will automatically find the registered
  // values and pass them in for you.
  public TaskController(
    ITaskRepository repository,
    ILogger logger)
  {
    this._repository = repository;
    this._logger = logger;
  }
}

 

 

 

 

 *****************************
 *** Keep learning and growing. ***
 *****************************

 

posted @ 2018-07-09 15:13  Gangle  阅读(151)  评论(0编辑  收藏  举报