ASP.NET注入服务或使用具有依赖注入的工厂

时间:2017-07-05 06:49:25

标签: asp.net dependency-injection autofac

我们目前在使用Autofac作为IoC容器在ASP.NET中开发的项目中首次使用依赖注入。

一切正常,但我们有一个关于将服务注入控制器的问题。

以下是一个例子:

ISupplierService

/// <summary>
/// Service interface for working with the <see cref="ISupplier"/>
/// </summary>
public interface ISupplierService
{
    /// <summary>
    /// Get the supplier by Id
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    ISupplier GetSupplierById(int id);
}

IArticleService

/// <summary>
/// Service interface when working with the <see cref="IArticle"/>
/// </summary>
public interface IArticleService
{
    /// <summary>
    /// Get article by id
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    IArticle GetArticleById(int id);
}

IoC注册服务

builder.RegisterAssemblyTypes(Assembly.Load("Project.Core"))
            .Where(t => t.Name.EndsWith("Service"))
            .AsImplementedInterfaces()
            .InstancePerLifetimeScope();

现在在我们的一个控制器中,我们需要供应商和物品服务,因此我们可以在控制器的构造函数中注入这两者。

public class HomeController : Controller
{
    private IArticleService _articleService;
    private ISupplierService _supplierService;

    public HomeController(IArticleService articleService, ISupplierService supplierService)
    {
        _articleService = articleService;
        _supplierService= supplierService;
    }
}

但是如果我们需要在控制器中使用4或5个服务甚至更多呢?

依赖注入创建某种服务工厂是不好的做法,我们使用Autofac解析所需服务的实例?通过这种方式,我们只需要在我们的控制器中注入工厂,然后我们可以在需要时从工厂调用正确的服务。

0 个答案:

没有答案
相关问题