Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added method to override default services lifetime #44

Merged
merged 1 commit into from
Nov 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions samples/PowerPipe.Sample/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,12 @@ private static IServiceProvider ConfigureServices()
//setup dependency injection
IServiceCollection services = new ServiceCollection();

services.AddPowerPipe(c =>
services.AddPowerPipe(config =>
{
c.RegisterServicesFromAssemblies(Assembly.GetExecutingAssembly())
.AddBehavior(typeof(SampleGenericStep<>), ServiceLifetime.Scoped);
config
.RegisterServicesFromAssemblies(Assembly.GetExecutingAssembly())
.ChangeDefaultLifetime(ServiceLifetime.Scoped)
.AddBehavior(typeof(SampleGenericStep<>), ServiceLifetime.Singleton);
});

services.AddSingleton<SamplePipeline>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,24 @@ public class PowerPipeConfiguration
internal ICollection<Assembly> AssembliesToRegister { get; } = new List<Assembly>();

internal ICollection<ServiceDescriptor> BehaviorsToRegister { get; } = new List<ServiceDescriptor>();


internal ServiceLifetime DefaultLifetime { get; private set; } = ServiceLifetime.Transient;

/// <summary>
/// Changes default (Transient) service registration life time
/// </summary>
/// <param name="lifetime"></param>
/// <returns></returns>
public PowerPipeConfiguration ChangeDefaultLifetime(ServiceLifetime lifetime)
{
if (DefaultLifetime == lifetime)
return this;

DefaultLifetime = lifetime;

return this;
}

/// <summary>
/// Register assembly to search implementations of steps from
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,18 @@ private static void ConnectImplementationsToTypes(

foreach (var type in exactMatches.Where(type => configuration.BehaviorsToRegister.All(c => c.ImplementationType != type)))
{
services.TryAddTransient(type);
switch (configuration.DefaultLifetime)
{
case ServiceLifetime.Singleton:
services.TryAddSingleton(type);
break;
case ServiceLifetime.Scoped:
services.TryAddScoped(type);
break;
case ServiceLifetime.Transient:
services.TryAddTransient(type);
break;
}
}

if (!inf.IsOpenGeneric())
Expand Down
Loading