JasperFx / lamar

Fast Inversion of Control Tool and Successor to StructureMap
https://jasperfx.github.io/lamar
MIT License
568 stars 119 forks source link

ConnectImplementationsToTypesClosing does not seem to work (or I do not understand what it is supposed to do) #160

Closed dcarapic closed 5 years ago

dcarapic commented 5 years ago

I'm tryin to get Lamar (3.0.3) to work in my .NET Core (2.2) web application and I can not make it resolve/generate correct implementation class. Here is a small console application which uses Lamar to get an instance of a class (.NET Core 2.2 with Lamar 3.0.3):

using System;
using System.Threading;
using System.Threading.Tasks;

namespace LamarTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var container = new Lamar.Container(cfg => {
                cfg.Scan(_ => {
                    _.AssemblyContainingType(typeof(Program));
                    _.ConnectImplementationsToTypesClosing(typeof(INotificationHandler<>));
                });
                //cfg.For(typeof(INotificationHandler<>)).Add(typeof(SignalRDomainEventHandler<>));
            });
            var instance = container.GetInstance(typeof(INotificationHandler<IDomainEvent>));
            Console.WriteLine(instance);
        }
    }

    public interface INotification {

    }

    public interface IDomainEvent : INotification {

    }

    public interface INotificationHandler<in TNotification> where TNotification : INotification
    {
        Task Handle(TNotification notification, CancellationToken cancellationToken);
    }    

    public class SignalRDomainEventHandler<T> : INotificationHandler<T> where T: IDomainEvent
    {

        public Task Handle(T notification, CancellationToken cancellationToken)
        {
            Console.WriteLine("Handled");
            return Task.CompletedTask;
        }
    }
}

The application has an interface INotificationHandler and single implementing class. If you run this you will get an exception:

Unhandled Exception: Lamar.IoC.LamarMissingRegistrationException: No service registrations exist or can be derived for LamarTest.INotificationHandler<LamarTest.IDomainEvent>
   at Lamar.IoC.Scope.GetInstance(Type serviceType)
   at LamarTest.Program.Main(String[] args) in C:\Work\Projects\OP\OP.BusinessRunner2\LamarTest\Program.cs:line 18

However if you uncomment line 16 (//cfg.For(typeof(INotificationHandler<>)).Add(typeof(SignalRDomainEventHandler<>));) then everything works fine. Did I misunderstand what ConnectImplementationsToTypesClosing does? Do I have to manually perform type mapping by scanning through the types myself?

dcarapic commented 5 years ago

Please ignore this issue. The method name states ...Closing which obviously means it will not route to my open handler. Sorry.