ipjohnson / Grace

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

Dependency properties don't work with keys #119

Closed RandomEngy closed 6 years ago

RandomEngy commented 6 years ago

Dependency properties don't seem to work with keys.

public class Test : ITest
{
    [Import(Key = "abc")]
    public IDep MyDep1 { protected get; set; }

    [Import(Key = "def")]
    public IDep MyDep2 { protected get; set; }

    public void DoAThing()
    {
        Console.WriteLine("Did a thing");
    }
}

...

var container = new DependencyInjectionContainer();
container.Configure(c => c.ImportMember<object>(MembersThat.HaveAttribute<ImportAttribute>()));
container.Configure(c => c.Export<Dep1>().AsKeyed<IDep>("abc"));
container.Configure(c => c.Export<Dep2>().AsKeyed<IDep>("def"));
container.Configure(c => c.Export<Test>().As<ITest>());

IDep myDep = container.Locate<IDep>(withKey: "abc"); // Works
ITest test = container.Locate<ITest>(); // Fails, can't import the dependency property

Exception is:

Grace.DependencyInjection.Exceptions.LocateException: 'Could not locate Type TestConsoleApp.IDep

ipjohnson commented 6 years ago

I see why that didn't work. The ImportMembers isn't taking into account the ImportAttribute it's only being used for filtering purposes (i.e the ImportAttribute isn't being inspected).

RandomEngy commented 6 years ago

This code is still failing for me in 6.3.0.

Grace.DependencyInjection.Exceptions.LocateException: 'Could not locate Type TestConsoleApp.IDep

1 Importing TestConsoleApp.ITest

2 Importing TestConsoleApp.IDep for property MyDep1

ipjohnson commented 6 years ago

Hmm now I'm a little flummexed because I added the following unit test for this use case.

Maybe it's a matter of ImportMembers() vs ImportMembers<T>()

Just to check the ImportAttribute we are talking about is the one found in Grace not the ImportAttribute from MEF?

RandomEngy commented 6 years ago

Oh my bad, I was doing ImportMember<T> instead of ImportMembers<T> . It's working now.

ipjohnson commented 6 years ago

Just to come full circle on why ImportMember<T> didn't work, I marked the old method as Obsolete because the naming convention is different than the one in Export<T> and left the old functionality the exact same (not processing attributes as I didn't want to introduce new behavior and break older code).