【问题标题】:How to implement Unity Container DI in Azure Function v2如何在 Azure Function v2 中实现 Unity Container DI
【发布时间】:2019-08-02 06:00:07
【问题描述】:

在 WebAPI 的早期,我曾经实现 Unity 容器依赖注入,如下所示

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        //I want to implement below in Azure Function V2
        var container = new UnityContainer();
        container.RegisterType<IDeviceRepository, DeviceRepository>(new HierarchicalLifetimeManager());
        container.RegisterType<IFilterRepository, FilterRepository>(new HierarchicalLifetimeManager());
        container.RegisterType<INEORepository, NEORepository>(new HierarchicalLifetimeManager());

        config.DependencyResolver = new UnityResolver(container); 
    }
}

如何在 Azure Function V2 中实现上述代码。

我浏览了几篇在线文章,但没有得到正确的解决方案。

请提出建议。

【问题讨论】:

  • 现在作为服务开箱即用。你检查过官方文档吗? docs.microsoft.com/en-us/azure/azure-functions/…
  • Azure 功能基于 aspnet 核心,因此您可以使用自己的 DI 容器或使用默认集成
  • azure 函数是指小的、离散的功能块。向其中注入服务是一种反模式,尽管它为您提供了这种能力

标签: c# azure asp.net-core .net-core azure-functions


【解决方案1】:

我使用下面的代码在 Azure 函数中实现 DI。

  public class GenericDependencyInjection
    {
        private static readonly UnityContainer UnityContainer = new UnityContainer();

        public GenericDependencyInjection()
        {
            try
            {
                UnityContainer.RegisterType<IOperations,Operations>(new ContainerControlledLifetimeManager());
            }
            catch (Exception ex)
            {
                throw ;
            }
        }

          public T Retrieve<T>()
        {
            return UnityContainer.Resolve<T>();
        }

        }

我通过在其他类中传递如下泛型类型来调用 Retrieve 方法

var data = new GenericDependencyInjection().Retrieve<EmpDetails>();
            return await data.UpdateDetails(EmpId, Name); //calling class EmpDetails method 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-16
    • 1970-01-01
    • 1970-01-01
    • 2019-05-08
    • 1970-01-01
    • 2019-06-11
    • 2020-04-09
    • 2019-09-01
    相关资源
    最近更新 更多