-
Notifications
You must be signed in to change notification settings - Fork 31
Closed
Labels
Description
Multiple Keyed (Named?) Instances. Constructor wants a specific key. Grace injects the wrong instance. Am I doing something wrong? See //returns Mongo below...
.Net Core (NetStandar 2.0)
Grace 6.4.0
using System;
using Grace.DependencyInjection;
using Grace.DependencyInjection.Attributes;
namespace test
{
class Program
{
static void Main(string[] args)
{
DatabaseFactory SqlServer = new DatabaseFactory() {name = "SqlServer"};
DatabaseFactory Oracle = new DatabaseFactory() {name = "Oracle"};
DatabaseFactory Mongo = new DatabaseFactory() {name = "Mongo"};
var container = new DependencyInjectionContainer();
container.Configure(c =>
{
c.ExportInstance(SqlServer).As<IDatabaseFactory>().AsKeyed<IDatabaseFactory>(SqlServer.name);
c.ExportInstance(Oracle).As<IDatabaseFactory>().AsKeyed<IDatabaseFactory>(Oracle.name);
c.ExportInstance(Mongo).As<IDatabaseFactory>().AsKeyed<IDatabaseFactory>(Mongo.name);
c.Export<TestDal>().As<ITestDal>();
});
IDatabaseFactory dbFactory = container.Locate<IDatabaseFactory>(withKey: "SqlServer");
if (dbFactory.name != "SqlServer") //works
throw new Exception("wrong dbFactory");
var testDal = container.Locate<ITestDal>();
if (testDal.DatabaseFactory.name != "SqlServer") //returns Mongo
throw new Exception("wrong database in Dal");
}
}
public interface IDatabaseFactory
{
string name { get; set; }
}
public class DatabaseFactory : IDatabaseFactory
{
public string name { get; set; }
}
public interface ITestDal
{
IDatabaseFactory DatabaseFactory { get; }
}
public class TestDal : ITestDal
{
private IDatabaseFactory _databaseFactory;
public TestDal([Import(Key = "SqlServer")] IDatabaseFactory techXpress)
{
_databaseFactory = techXpress;
}
public IDatabaseFactory DatabaseFactory
{
get { return _databaseFactory; }
}
}
}