Ist es möglich, dieselbe Schnittstelle zweimal zu registrieren, wobei die erste zu einer Standardimplementierung aufgelöst wird und die zweite einen Namen hat und in einen anderen Typ aufgelöst wird.Kann der Einheits-Container den Standardtyp auflösen, wenn der Name nicht gefunden wird?
Beispiel:
container.RegisterType(typeof(IMyInterface), typeof(MyDefaultImplementation));
container.RegisterType(typeof(IMyInterface), typeof(MySecondImplementation),"Second Implementations name");
So
Resolve<IMyInterface>("non existing name")
Sollte MyDefaultImplementation lösen.
public class DefaultRegistrationFallbackConfiguration : UnityContainerExtension
{
protected override void Initialize()
{
this.Context.Registering += this.AppendRemapPolicy;
}
public override void Remove()
{
this.Context.Registering -= this.AppendRemapPolicy;
}
private void AppendRemapPolicy(object sender, RegisterEventArgs e)
{
if (e.Name != null)
return;
if (e.TypeFrom != null && e.TypeTo != null)
this.Context.Policies.SetDefault<IBuildKeyMappingPolicy>(new MapBuildKeyToDefaultPolicy(e.TypeFrom, e.TypeTo));
if (e.LifetimeManager == null)
return;
throw new NotImplementedException("TODO: lifetime management");
}
}
Erstellen Sie Ihre eigenen IBuildKeyMappingPolicy
:
public class MapBuildKeyToDefaultPolicy : IBuildKeyMappingPolicy
{
private readonly Type _typeFrom;
private readonly Type _typeTo;
public MapBuildKeyToDefaultPolicy(Type typeFrom, Type typeTo)
{
this._typeFrom = typeFrom;
this._typeTo = typeTo;
}
public NamedTypeBuildKey Map(NamedTypeBuildKey buildKey, IBuilderContext context)
{
if (buildKey.Type == this._typeFrom)
return new NamedTypeBuildKey(this._typeTo);
throw new InvalidOperationException();
}
}
Test-Klassen, die Sie besitzen Konfiguration, fügen Sie es als Erweiterung
Ja, Sie Ihre benutzerdefinierte erstellen 'BuilderStrategy'. Sie können sich die akzeptierte Antwort zu dieser Frage ansehen. Aber Sie sollten vielleicht noch einmal überdenken, ob es tatsächlich das ist, was Sie tun möchten ... http://stackoverflow.com/questions/1380375/custom-object-factory-extension-for-unity – smoksnes