Autofac 和 ASP .Net MVC 4 Web API

2023-11-22

我在用Autofac用于我的 ASP .Net MVC 4 项目中的 IoC。 Autofac 在初始化存储库并将其传递到API控制器.

我确信我的配置中缺少某些内容。

这是我导航到时遇到的错误:https://localhost:44305/api/integration

<Error>
    <Message>An error has occurred.</Message>
    <ExceptionMessage>
        None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' 
        on type 'EL.Web.Controllers.API.IntegrationController' can be invoked with 
        the available services and parameters: Cannot resolve parameter 
        'EL.Web.Infrastructure.IRepository`1[EL.Web.Models.Integration] repository' of 
        constructor 'Void .ctor(EL.Web.Infrastructure.IRepository`1[EL.Web.Models.Integration])'.
    </ExceptionMessage>
    <ExceptionType>Autofac.Core.DependencyResolutionException</ExceptionType>
    <StackTrace>
        at Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable`1 parameters) 
        at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters) 
        at Autofac.Core.Resolving.InstanceLookup.Execute() 
        at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable`1 parameters) 
        at Autofac.Core.Resolving.ResolveOperation.ResolveComponent(IComponentRegistration registration, IEnumerable`1 parameters) 
        at Autofac.Core.Resolving.ResolveOperation.Execute(IComponentRegistration registration, IEnumerable`1 parameters) 
        at Autofac.Core.Lifetime.LifetimeScope.ResolveComponent(IComponentRegistration registration, IEnumerable`1 parameters) 
        at Autofac.ResolutionExtensions.TryResolveService(IComponentContext context, Service service, IEnumerable`1 parameters, Object& instance) 
        at Autofac.ResolutionExtensions.ResolveOptionalService(IComponentContext context, Service service, IEnumerable`1 parameters) 
        at Autofac.ResolutionExtensions.ResolveOptional(IComponentContext context, Type serviceType, IEnumerable`1 parameters) 
        at Autofac.ResolutionExtensions.ResolveOptional(IComponentContext context, Type serviceType) 
        at Autofac.Integration.WebApi.AutofacWebApiDependencyScope.GetService(Type serviceType) 
        at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator) 
        at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
    </StackTrace>
</Error>

以下是一些相关的代码:

IoC 引导程序:

public static class Bootstrapper
{
    public static void Initialize()
    {
        var builder = new ContainerBuilder();

        builder.RegisterControllers(Assembly.GetExecutingAssembly());
        builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

        builder.Register(x => new SharePointContext(HttpContext.Current.Request)).As<ISharePointContext>().SingleInstance();
        builder.RegisterType<SharePointRepository<IEntity>>().As<IRepository<IEntity>>();
        builder.RegisterType<SharePointContextFilter>().SingleInstance();

        builder.RegisterFilterProvider();

        IContainer container = builder.Build();
        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

        var resolver = new AutofacWebApiDependencyResolver(container);
        GlobalConfiguration.Configuration.DependencyResolver = resolver;
    }
}

我的存储库:

public interface IRepository<T>
{
    void Add(T entity);

    void Delete(int id);

    IEnumerable<T> Find(Expression<Func<T, bool>> filter = null);

    void Update(int id, T entity);
}

SharePoint 存储库:

internal class SharePointRepository<T> : IRepository<T> where T : IEntity
{
    private readonly ISharePointContext _context;
    private readonly string _listName;

    internal SharePointRepository(ISharePointContext context)
    {
        _context = context;

        object[] attributes = typeof (T).GetCustomAttributes(typeof (SharePointListAttribute), false);

        if (!attributes.Any())
        {
            throw new Exception("No associated SharePoint list defined for " + typeof (T));
        }

        _listName = ((SharePointListAttribute) attributes[0]).ListName;
    }

    public void Add(T entity)
    {
        throw new NotImplementedException();
    }

    public void Delete(int id)
    {
        throw new NotImplementedException();
    }

    public IEnumerable<T> Find(Expression<Func<T, bool>> filter)
    {
        throw new NotImplementedException();
    }

    public void Update(int id, T entity)
    {
        throw new NotImplementedException();
    }
}

集成控制器:

public class IntegrationController : ApiController
{
    private readonly IRepository<Integration> _repository;

    public IntegrationController(IRepository<Integration> repository)
    {
        _repository = repository;
    }

    public void Delete(Guid integrationId)
    {
        _repository.Delete(Get(integrationId).Id);
    }

    public IEnumerable<Integration> Get()
    {
        return _repository.Find();
    }

    public Integration Get(Guid integrationId)
    {
        return _repository.Find(i => i.IntegrationId == integrationId).FirstOrDefault();
    }

    public void Post([FromBody] Integration integration)
    {
        _repository.Add(integration);
    }

    public void Put(Guid integrationId, [FromBody] Integration integration)
    {
        _repository.Update(Get(integrationId).Id, integration);
    }
}

IEntity:

internal interface IEntity
{
    int Id { get; }
}

Entity:

public abstract class Entity : IEntity
{
    protected Entity(int id)
    {
        Id = id;
    }

    public int Id { get; private set; }
}

一体化:

[SharePointList("Integrations")]
public class Integration : Entity
{
    public Integration(int id) : base(id)
    {
    }

    public string ApiUrl { get; set; }

    public bool DeletionAllowed { get; set; }

    public Guid IntegrationId { get; set; }

    public string Key { get; set; }

    public string List { get; set; }

    public bool OutgoingAllowed { get; set; }

    public string RemoteWeb { get; set; }

    public string Web { get; set; }
}

您已注册您的IRepository错误的。用行:

builder.RegisterType<SharePointRepository<IEntity>>().As<IRepository<IEntity>>();

你告诉 Autofac 每当有人要求IRepository<IEntity>给他们一个SharePointRepository<IEntity>,但你要求一个具体的IRepository<Integration>所以你会得到一个例外。

你需要的是开放Autofac通用注册功能。因此,将您的注册更改为:

builder.RegisterGeneric(typeof(SharePointRepository<>))
       .As(typeof(IRepository<>));

当您要求时,它将按照您所期望的方式工作IRepository<Integration>它会给一个SharePointRepository<Integration>.

您还有第二个不相关的问题:您的SharePointRepository只有一个internal构造函数。

Autofac 默认情况下只查找public构造函数,因此您可以将构造函数和类更改为public或者你需要告诉 Autofac 寻找 NonPublic 构造函数FindConstructorsWith method:

builder
    .RegisterType<SharePointRepository<IEntity>>()
    .FindConstructorsWith(
       new DefaultConstructorFinder(type => 
          type.GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance))) 
    .As<IRepository<IEntity>>();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Autofac 和 ASP .Net MVC 4 Web API 的相关文章

随机推荐

  • 如何在 Markdown 中为 PDF 文档添加图像作为页眉/页脚

    我想将图像作为页眉和页脚 与我的组织的视觉标识保持一致 添加到 PDF 报告中 我已经设法在 Sweave 中做到这一点 但我也希望能够仅使用 Markdown 来做到这一点 我可以使用插入图像 footer H R Footer pdf
  • C# .NET - 固定证书颁发机构 - 我做得正确吗?

    我的软件使用 HTTPS 连接连接到 Dropbox 以检索一些敏感数据 我想固定证书颁发机构以防止中间人攻击 到目前为止我有以下代码 static bool VerifyServerCertificate object sender X5
  • 独立于AWS Lambda函数的Python子进程

    我已成功创建一个读取和写入 RDS 的 Lambda 函数 app1 我的Lambda函数是用python2 7编写的 并作为压缩包上传 我在与 RDS 和 Lambda 函数相同的 VPC 中的 EC2 实例上创建并测试了压缩包 接下来
  • CSS 中的负边距如何工作以及为什么是 (margin-top:-5 != margin-bottom:5)?

    垂直定位元素的一个常见技巧是使用以下 CSS item position absolute top 50 margin top 8px half of height height 16px 当在 Chrome 中的指标视图中看到时 您会看到
  • 如何在 SVG 矩形中放置文本并使其居中

    我有以下矩形
  • git删除了所有内容,如何恢复文件和文件夹

    这是我第一次使用git 我想将现有的项目导入github 然后所有内容都被删除了 搜索答案后 我认为 git 在 git pull 后删除了文件 我正在尝试恢复文件和文件夹 但我找不到如何执行此操作 我做了下一个 jesus jesus K
  • 数值向量运算符重载+右值引用参数

    我有下面的数值向量模板类 用于数值计算的向量 我正在努力让它成为可能D A B C所有变量都是Vector对象 A B and C不应修改 我的想法是使用Vector operator Vector B 这样在 希望 Rvalue 之后Ve
  • java.lang.ClassCastException:android.view.ViewGroup$LayoutParams 无法转换为 android.widget.Gallery$LayoutParams

    我正在尝试添加Fancycoverflow在我的应用程序中 它可以很好地处理静态图像 如这个例子 但我在适配器中做了一些更改 我尝试运行我的应用程序 它崩溃并显示以下错误 FATAL EXCEPTION main java lang Cla
  • 如何使用前缀/后缀重命名?

    我该怎么做mv original filename new original filename无需重新输入原始文件名 我想象能够做类似的事情mv p new original filename也许mv original filename n
  • Java 关键字作为变量

    在VB NET中 我们可以用括号将变量名括起来 并使用关键字作为变量名 如下所示 Dim new As String C 等效项 string new 我想知道 Java 是否有相当于这样做的东西 不可以 您可以添加下划线或类似的废话 但基
  • 没有catalina.out

    我不知道如何设置以及设置什么 以便在我的计算机上的 Tomcat 上安装 catalina out 我在 Windows XP 上使用 Tomcat 6 0 28 压缩版本 要启动服务器 我只需运行startup bat file 难道我做
  • 我可以在gdb下打印gdtr和gdt描述符吗?

    I want to use gdb to see my GDTR LDTR TTR and segment register 不可见部分 x86 所以在 gdb 中我输入 p x gdtr 等 但结果是 6 值无法转换为整数 在 gdb 中
  • C 和 C++ 编码标准

    关于 C 和 C 编码标准的最佳实践是什么 是否应该允许开发人员随意将它们混合在一起 链接 C 和 C 目标文件时是否存在任何复杂情况 像传统上用 C 编写的套接字库之类的东西是否应该保留在 C 中并保存在单独的源文件中 即将 c 代码保存
  • Django CSRF 检查因 Ajax POST 请求而失败

    我可以通过我的 AJAX 帖子获得一些遵守 Django 的 CSRF 保护机制的帮助 我已按照此处的说明进行操作 http docs djangoproject com en dev ref contrib csrf 我已经准确地复制了该
  • ARKit 1.5 如何获取垂直平面的旋转

    我正在尝试垂直平面 并尝试将节点放置在墙上 并根据该垂直平面进行正确的旋转 这是被点击的垂直平面的 ARHitTestResult let hitLocation sceneView hitTest touchPoint types exi
  • 在没有互联网连接的计算机上使用 Scala

    我是 Scala 新手 如果问题绝对显而易见 我很抱歉 我的计算机上安装了 Eclipse Photon 想要编辑 Scala 代码并生成可运行的 jar 棘手的部分是我的计算机 Centos7 无法访问互联网 我记住两个潜在的问题 手动下
  • 如何在具有角度嵌套数据组的材料表中显示拆分标题

    当数据作为对象的嵌套数组出现时 我在材料表中显示数据时遇到问题 我想显示当前显示在 stackblitz 中的表格 如果我用我的更改现有数据newData变量它将开始破坏整个表 谁能指导我如何通过材料表中的一组嵌套数据实现拆分标题功能 我想
  • iPad 上具有自定义尺寸的 SwiftUI Sheet() 模式

    如何使用 SwiftUI 控制 iPad 上模态表的首选演示大小 我很惊讶在谷歌上找到这个问题的答案是多么困难 另外 了解模式是否通过向下拖动 取消 或实际执行自定义积极操作来关闭的最佳方法是什么 以下是我在 iPad 上使用 SwiftU
  • 找出两个缺失的数字

    我们有一台内存为 O 1 的机器 我们想要通过n第一遍中的数字 一个接一个 然后我们排除这两个数字 我们将通过n 2号码到机器 编写一个算法来查找缺失的数字 可以使用 O 1 内存来完成 您只需要几个整数来跟踪一些运行总和 整数不需要 lo
  • Autofac 和 ASP .Net MVC 4 Web API

    我在用Autofac用于我的 ASP Net MVC 4 项目中的 IoC Autofac 在初始化存储库并将其传递到API控制器 我确信我的配置中缺少某些内容 这是我导航到时遇到的错误 https localhost 44305 api