Ich glaube, Sie besser Autofac verlängern würde durch eine neue Lebensdauer Option einzuführen. Ich nahm die Autofac Quellen und modifiziert sie ein wenig:
public static class RegistrationBuilderExtensions
{
public IRegistrationBuilder<TLimit, TActivatorData, TRegistrationStyle> InstancePerMatchingOrRootLifetimeScope(this IRegistrationBuilder<TLimit, TActivatorData, TRegistrationStyle> builder, params object[] lifetimeScopeTag)
{
if (lifetimeScopeTag == null) throw new ArgumentNullException("lifetimeScopeTag");
builder.RegistrationData.Sharing = InstanceSharing.Shared;
builder.RegistrationData.Lifetime = new MatchingScopeOrRootLifetime(lifetimeScopeTag);
return builder;
}
}
public class MatchingScopeOrRootLifetime: IComponentLifetime
{
readonly object[] _tagsToMatch;
public MatchingScopeOrRootLifetime(params object[] lifetimeScopeTagsToMatch)
{
if (lifetimeScopeTagsToMatch == null) throw new ArgumentNullException("lifetimeScopeTagsToMatch");
_tagsToMatch = lifetimeScopeTagsToMatch;
}
public ISharingLifetimeScope FindScope(ISharingLifetimeScope mostNestedVisibleScope)
{
if (mostNestedVisibleScope == null) throw new ArgumentNullException("mostNestedVisibleScope");
var next = mostNestedVisibleScope;
while (next != null)
{
if (_tagsToMatch.Contains(next.Tag))
return next;
next = next.ParentLifetimeScope;
}
return mostNestedVisibleScope.RootLifetimeScope;
}
}
Fügen Sie einfach diese Klassen zu einem Projekt und registrieren Sie Komponente wie:
builder.RegisterType<A>.InstancePerMatchingOrRootLifetimeScope("TAG");
ich es selbst nicht ausprobiert haben, aber es sollte funktionieren .
Warum brauchen Sie das? Möchten Sie, dass die globale Registrierung von der Bereichsregistrierung abweicht? Oder möchten Sie, dass Verbraucher in einem Fall eine Instanz und in anderen Fällen andere Instanzen erhalten, während die Konfigurationen sowohl für den globalen als auch für den markierten Bereich gleich bleiben? –
@PavelGatilov Letzteres. Gleiche Konfiguration, unterschiedliche Instanz für jeden markierten Bereich und unterschiedliche Instanz für globalen Bereich. –