首页 > 解决方案 > 在 .net core 中为不同的依赖注入容器编写一个包装器

问题描述

我想在我的.net 核心项目中围绕依赖注入容器编写一个包装器,这样每当我需要在我的应用程序中注入某些东西时,我就可以使用我自己的注入器,它实际上是使用AutofacSimpleInjection等第三方容器进行注入。这样我就可以改变我的注射器,而无需改变我的代码

我为此目的编写了一个接口,其中包含一些需要的方法:

  interface IDependencyBuilder
    {
        void CreateContainer();

        IContainer Build();

        void RegisterModule<T>() where T : Module, new();

    }

我已经为Autofac实现了它,如下所示:

public class AutofacContainerBuilder : IDependencyBuilder
    {
        private readonly ContainerBuilder _containerBuilder;

        public AutofacContainerBuilder()
        {
            _containerBuilder = new ContainerBuilder();
        }
        public void CreateContainer()
        {
            throw new NotImplementedException();
        }
        public IContainer Build()
        {
            return _containerBuilder.Build();
        }

        public void RegisterModule<T>() where T : Autofac.Module,new()
        {
            _containerBuilder.RegisterModule<T>();
        }
    }

我认为这种实现和编写包装器有问题。

1 . 签名和输入/输出模型:我不完全知道应该在包装器中写入哪些具有哪些签名的函数。

2 . 不同第三方的实现:为了创建一个容器,我必须在构造函数中拥有它,并且无法实现创建容器方法。

我希望用我的包装器处理我的模块化应用程序中的依赖注入。

为模块化 Web 应用程序执行此操作的正确方法是什么?

标签: c#reflectiondependency-injection.net-corewrapper

解决方案


推荐阅读