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

Add Lazy Proxy support #20

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
Open
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
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,25 @@ services.AddServicesFrom("MyCompany.ProjectName.Repositories.Concrete"); // <--
- That's it! DotNurse can find your namespace from any assembly. You don't need to send any Assembly parameter.


***

## Using Lazy Proxy
DotNurse Injector supports lazy proxies for better performance at runtime. When it used, injected object won't be created until first usage of it.
Visit the github page of [lazy-proxy](https://github.com/servicetitan/lazy-proxy) for better understanding.


### Usage
Configuring `UseLazyProxy` as **true** provides registering services with LazyProxy:


```csharp
services.AddServicesFrom("MyProject.Namespace", ServiceLifetime.Transient, opts => opts.UseLazyProxy = true);

// OR

services.AddServicesByAttributes(useLazyProxy: true);
```

***

## Property/Field Injection
Expand Down
1 change: 1 addition & 0 deletions src/DotNurse.Injector/DotNurse.Injector.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="LazyProxy" Version="1.0.2" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="6.0.0" />
</ItemGroup>

Expand Down
12 changes: 12 additions & 0 deletions src/DotNurse.Injector/DotNurseInjectorContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using DotNurse.Injector.Registration;
using DotNurse.Injector.Services;

namespace DotNurse.Injector
{
public class DotNurseInjectorContext
{
public ITypeExplorer TypeExplorer { get; set; } = new DotNurseTypeExplorer();

public ILazyServiceDescriptorCreator LazyServiceDescriptorCreator { get; set; } = new DotNurseInjectorLazyServiceDescriptorCreator();
}
}
5 changes: 5 additions & 0 deletions src/DotNurse.Injector/DotNurseInjectorOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@ public class DotNurseInjectorOptions
/// </summary>
public Assembly Assembly { get; set; }

/// <summary>
/// Uses lazy proxy if set true. By default it's <see cref="false"/>.
/// </summary>
public bool UseLazyProxy { get; set; }

/// <summary>
/// Filter objects by name with given algorithm.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using LazyProxy;
using Microsoft.Extensions.DependencyInjection;
using System;

namespace DotNurse.Injector.Registration
{
public class DotNurseInjectorLazyServiceDescriptorCreator : ILazyServiceDescriptorCreator
{
public virtual ServiceDescriptor Create(Type serviceType, Type implementationType, ServiceLifetime lifetime)
{
var factory = ActivatorUtilities.CreateFactory(implementationType, Array.Empty<Type>());

return new ServiceDescriptor(
serviceType,
(s) => LazyProxyBuilder.CreateInstance(serviceType, () => factory(s, null)),
lifetime);
}
}
}
10 changes: 10 additions & 0 deletions src/DotNurse.Injector/Registration/ILazyServiceRegistrar.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
using Microsoft.Extensions.DependencyInjection;
using System;

namespace DotNurse.Injector.Registration
{
public interface ILazyServiceDescriptorCreator
{
ServiceDescriptor Create(Type serviceType, Type implementationType, ServiceLifetime lifetime);
}
}
43 changes: 32 additions & 11 deletions src/DotNurse.Injector/Startup.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using DotNurse.Injector.Attributes;
using DotNurse.Injector.Registration;
using DotNurse.Injector.Services;
using LazyProxy;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
Expand All @@ -10,7 +12,7 @@ namespace DotNurse.Injector;

public static class Startup
{
private static ITypeExplorer TypeExplorer { get; } = new DotNurseTypeExplorer();
private static DotNurseInjectorContext Context { get; } = new DotNurseInjectorContext();

public static IServiceCollection AddServicesFrom(this IServiceCollection services,
string @namespace,
Expand All @@ -20,7 +22,7 @@ public static class Startup
var options = new DotNurseInjectorOptions();
configAction?.Invoke(options);

var types = TypeExplorer.FindTypesInNamespace(@namespace, options.Assembly);
var types = Context.TypeExplorer.FindTypesInNamespace(@namespace, options.Assembly);

services.RegisterTypes(types, defaultLifetime, options);

Expand All @@ -35,13 +37,14 @@ public static class Startup
public static IServiceCollection AddServicesByAttributes(
this IServiceCollection services,
ServiceLifetime defaultServiceLifetime = ServiceLifetime.Transient,
bool useLazyProxy = false,
Assembly assembly = null)
{
var types = TypeExplorer.FindTypesWithAttribute<RegisterAsAttribute>(assembly);
var types = Context.TypeExplorer.FindTypesWithAttribute<RegisterAsAttribute>(assembly);

foreach (var type in types)
foreach (var injectAsAttribute in type.GetCustomAttributes<RegisterAsAttribute>())
services.Add(new ServiceDescriptor(injectAsAttribute.ServiceType, type, injectAsAttribute.ServiceLifetime ?? defaultServiceLifetime));
services.Add(CreateServiceDescriptor(injectAsAttribute.ServiceType, type, injectAsAttribute.ServiceLifetime ?? defaultServiceLifetime, useLazyProxy));

return services;
}
Expand All @@ -55,15 +58,17 @@ public static class Startup
var options = new DotNurseInjectorOptions();
configAction?.Invoke(options);

var types = TypeExplorer.FindTypesByExpression(expression, options.Assembly);
var types = Context.TypeExplorer.FindTypesByExpression(expression, options.Assembly);

services.RegisterTypes(types, defaultServiceLifetime, options);
return services;
}

public static IServiceCollection AddDotNurseInjector(this IServiceCollection services)
public static IServiceCollection AddDotNurseInjector(this IServiceCollection services, Action<DotNurseInjectorContext> contextAction = null)
{
services.AddSingleton<ITypeExplorer, DotNurseTypeExplorer>();
contextAction?.Invoke(Context);
services.Add(new ServiceDescriptor(typeof(ITypeExplorer), Context.TypeExplorer.GetType(), ServiceLifetime.Singleton));
services.Add(new ServiceDescriptor(typeof(ILazyServiceDescriptorCreator), Context.LazyServiceDescriptorCreator.GetType(), ServiceLifetime.Transient));
return services;
}

Expand Down Expand Up @@ -94,12 +99,12 @@ public static IServiceCollection AddDotNurseInjector(this IServiceCollection ser

var interfaces = type.GetInterfaces();

services.Add(new ServiceDescriptor(type, type, lifetime));
services.Add(CreateServiceDescriptor(type, type, lifetime, options.UseLazyProxy));

if (interfaces.Length == 1)
{
var inheritFrom = interfaces.FirstOrDefault();
services.Add(new ServiceDescriptor(inheritFrom, type, lifetime));
services.Add(CreateServiceDescriptor(inheritFrom, type, lifetime, options.UseLazyProxy));

continue;
}
Expand All @@ -109,17 +114,33 @@ public static IServiceCollection AddDotNurseInjector(this IServiceCollection ser
{
foreach (var injectAsAttribute in registerAsAttribute)
if (!services.Any(a => a.ServiceType == injectAsAttribute.ServiceType))
services.Add(new ServiceDescriptor(injectAsAttribute.ServiceType, type, injectAsAttribute.ServiceLifetime ?? lifetime));
services.Add(CreateServiceDescriptor(injectAsAttribute.ServiceType, type, injectAsAttribute.ServiceLifetime ?? lifetime, options.UseLazyProxy));
continue;
}

if (interfaces.Length > 1)
{
services.Add(new ServiceDescriptor(options.SelectInterface(interfaces), type, lifetime));
services.Add(CreateServiceDescriptor(options.SelectInterface(interfaces), type, lifetime, options.UseLazyProxy));
continue;
}
}

return services;
}

private static ServiceDescriptor CreateServiceDescriptor(
Type serviceType,
Type implementationType,
ServiceLifetime lifetime = ServiceLifetime.Transient,
bool withLazyProxy = false)
{
if (withLazyProxy && serviceType.IsAbstract)
{
return Context.LazyServiceDescriptorCreator.Create(serviceType, implementationType, lifetime);
}
else
{
return new ServiceDescriptor(serviceType, implementationType, lifetime);
}
}
}
52 changes: 52 additions & 0 deletions tests/DotNurse.Injector.Tests/StartupTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -180,4 +180,56 @@ public void AddServicesFrom_RegisterRecursive_ShouldMatchCount()
Console.WriteLine(services.Count + " >= " + allTypesCount);
Assert.True(services.Count >= types.Count());
}

[Fact]
public void AddServicesFrom_ShouldAddCorrectCount_WithSingleInheritanceWithLazyProxy()
{
// Arrange
var services = new ServiceCollection();
var nameSpace = "DotNurse.Injector.Tests.Environment.NamespaceSingle";

// Act
services.AddServicesFrom(nameSpace, configAction: opts => opts.UseLazyProxy = true);

// Assert
Assert.Contains(services, x => x.ImplementationType == null && x.ImplementationFactory != null);
}

[Fact]
public void AddServicesByAttributes_ShouldAddImplementationFactoryForAbstracts_WithLazyProxy()
{
// Arrange
var services = new ServiceCollection();

// Registered Services: typeof(IComputer), typeof(ILaptop), typeof(MyLaptop)

// Act
services.AddServicesByAttributes(useLazyProxy: true);

// Assert
var serviceComputer = services.FirstOrDefault(x => x.ServiceType == typeof(IComputer));

Assert.Null(serviceComputer.ImplementationType);
Assert.NotNull(serviceComputer.ImplementationFactory);
}

[Fact]
public void AddServicesByAttributes_ShouldAddImplementationTypeForNonAbstracts_WithLazyProxy()
{
// Arrange
var services = new ServiceCollection();

// Registered Services: typeof(IComputer), typeof(ILaptop), typeof(MyLaptop)

// Act
services.AddServicesByAttributes(useLazyProxy: true);

// Assert
Assert.Contains(services, x => x.ImplementationType == typeof(MyLaptop) && x.ServiceType == typeof(MyLaptop));

var serviceComputer = services.FirstOrDefault(x => x.ImplementationType == typeof(MyLaptop));

Assert.Null(serviceComputer.ImplementationFactory);
Assert.NotNull(serviceComputer.ImplementationType);
}
}