【问题标题】:StructureMap does not see types in ASP.NET Core .NET5StructureMap 在 ASP.NET Core .NET5 中看不到类型
【发布时间】:2021-03-08 10:58:07
【问题描述】:

我正在创建基于 DDD 的示例项目。

  1. 我创建了 SharedKernel 项目,其中我有我的 DomainEvents 类
    public static class DomainEvents
    {
        public static IContainer Container { get; set; }

        static DomainEvents()
        {
            Container = StructureMap.Container.For<GenericTypesScanning>();
        }

        public static void Raise<T>(T args) where T : IDomainEvent
        {
            foreach (var handler in Container.GetAllInstances<IHandle<T>>())
            {
                handler.Handle(args);
            }
        }
     }

这是类 GenericTypesScanning

    public class GenericTypesScanning : Registry
    {
        public GenericTypesScanning()
        {
            Scan(scan =>
            {
                // 1. Declare which assemblies to scan
                scan.Assembly("MyLib");

                // 2. Built in registration conventions
                scan.AddAllTypesOf(typeof(IHandle<>));
                scan.WithDefaultConventions();

            });          

        }
    }
  1. MyLib 项目中,我有 AppointmentConfirmedEvent 类和此事件的处理程序:
    public class EmailConfirmationHandler: IHandle<AppointmentConfirmedEvent>
    {
        public void Handle(AppointmentConfirmedEvent appointmentConfirmedEvent)
        {
            // TBD
        }
    }
  1. 我有一个临时的 rest api 控制器,我想检查一切是否正确注册,我正在这样做:
    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        // GET: api/<ValuesController>
        [HttpGet]
        public IEnumerable<string> Get()
        {                        
            var appointmentConfirmedEvent = new AppointmentConfirmedEvent();
            DomainEvents.Raise(appointmentConfirmedEvent);

            return new string[] { "value1", "value2" };
        }
    }

但是当DomainEvents.Raise 被调用时,事件不会被处理,因为内部调用Container.GetAllInstances&lt;IHandle&lt;T&gt;&gt;() 返回空数组。

我用控制台应用做了类似的例子,一切正常。知道为什么它在 ASP.NET Core .NET 5 项目中不起作用吗?

-杰克

【问题讨论】:

    标签: c# asp.net-core structuremap


    【解决方案1】:

    AddAllTypesOf() 方法不适用于开放泛型。请参阅 StructureMap 文档中的 ConnectImplementationsToTypesClosing() 方法:http://structuremap.github.io/generics/

    提醒一下,StructureMap 不再受支持。此外,2.6.4.1 是 StructureMap 的“闹鬼”版本,无可否认存在漏洞。

    【讨论】:

      【解决方案2】:

      首先要做的是检查类型扫描诊断:

      http://structuremap.github.io/diagnostics/type-scanning/.

      如果缺少程序集,类型扫描可能会有点脆弱。诊断可能会指出哪里出了问题。另外,也请尝试您的WhatDoIHave() 诊断程序。

      此外,只需确保您知道 StructureMap 不再受支持并已被 Lamar 取代:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-12-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多