ipjohnson / Grace

Grace is a feature rich dependency injection container library
MIT License
336 stars 33 forks source link

Could not locate Service with Key #297

Closed XanNava closed 1 year ago

XanNava commented 1 year ago

Below is code I am using to test out Keyed Import/Export.

DependencyInjectionContainer container = new DependencyInjectionContainer((c) => {
    c.AutoRegisterUnknown = true;
    c.Trace = (s => {
        Console.WriteLine(s);
    });
});

container.Configure((c) => {
    c.Export<Service>().AsKeyed<IService>("ServiceMain");

    c.Export<ServiceAlt>().AsKeyed<IService>("ServiceAlt");
});

var scope = container.BeginLifetimeScope("RootScope");

var alt = container.Locate<IService>("ServiceAlt");

private interface IService {
    string GetString();
}

class Service : IService {
    public virtual string GetString() {
        return "Service";
    }
}

class ServiceAlt : IService {
    public string GetString() {
        return "Service AlternativeService";
    }
}

I am however getting the message.

Could not locate Type PlayGroundLibrary.Models.GraceTesting.Testing+IService

if I have just a c.Export<Service>().As<IService>(); I can get an instance of it, but the key still won't work, and just defaults to the none keyed entry.

Using Grace 8.0.0-Beta822

XanNava commented 1 year ago

Seems to happen with Grace version 7.2.1 also

XanNava commented 1 year ago

I figured it out. For reference one needs to use container.Locate<IService>(withKey: "ServiceA"); the withKey so it is used for the right argument.

ipjohnson commented 1 year ago

Sounds like this is solved