Skip to content

Feature Suggestion & PR: Support open generic types with factory func implementation #847

Description

@yoloroy

In my game I am using factory methods in my service to produce objects and delegates for the game system. I see that there are open generic type support right now, but it only supports openGenericType by implementationType resolution. Similarly to already existing factory func registrations, I am adding open generic type resolution by lambda.

I added support for open generic types with func implementations:

builder.Register
(
  interfaceType: typeof(IImpactConsumer<>),
  implementationFactory: (resolver, tImpact) =>
  {
    var intentsImpacts = resolver.Resolve<IntentsImpacts>();
    var affectable = resolver.ResolveOrDefault<IModifyingImpacts>();
    return intentsImpacts.GetImpactConsumerFor(gameObject, tImpact, affectable);
  },
  lifetime: Lifetime.Scoped
);

and

builder.Register
(
  interfaceType: typeof(PublishIntent<>),
  implementationFactory: (resolver, tIntent) =>
  {
    var intentsImpacts = resolver.Resolve<IntentsImpacts>();
    return intentsImpacts.GetIntentPublisher(tIntent);
  },
  lifetime: Lifetime.Scoped
);
How it was resovled before

Not the biggest change in line count in the LifecycleScope code, but previous solution was a hackaround.

Func<Type, Func<IObjectResolver, object>> impactConsumerProvider = tImpact => resolver =>
{
  var intentsImpacts = resolver.Resolve<IntentsImpacts>();
  var affectable = resolver.ResolveOrDefault<IModifyingImpacts>();
  return intentsImpacts.GetImpactConsumerFor(gameObject, tImpact, affectable);
};

foreach (var tImpact in CachedTypes.Impacts)
{
  var consumerType = typeof(IImpactConsumer<>).MakeGenericType(tImpact);
  var registration = new FuncRegistrationBuilder(impactConsumerProvider(tImpact), consumerType, Lifetime.Scoped);

  builder.Register(registration);
}

Usage for delegate and object injections:
[Inject] private PublishIntent<InfuseAreaWithChaosIntent> _cast;
[Inject] private IImpactConsumer<ReceivedStatusImpact> _newStatuses;

change: a5e105b
branch: https://github.com/yoloroy/VContainer/tree/add-generic-func-registration

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions