agoda-com / agoda-com/Agoda.IoC
Support Lazy Initialization for RegisterPerRequest
- 主要语言
- C#
- 星标
- 38
- 派生
- 10
- PR 合并指标
- 30 天内没有已合并 PR
描述
# Feature request
## Type
- [x] - Enhancement - completely new feature
## Is your feature request related to a problem?
A controller or a service can have many underlying services to handle different requests. For example, ControllerA can have MyService and MyService can have ServiceA, ServiceB and so on.

The problem with this is all services are not used for some requests. an RequestForA request can only use ServiceA, or RequestForB can only use ServiceB. However, all services get initialized.
```
public class MyService : IMyService
{
private readonly IServiceA _serviceA;
private readonly IServiceB _serviceB;
public MyService(IServiceA serviceA, IServiceB serviceB)
{
_serviceA = serviceA;
_serviceB = serviceB;
}
public void DoWorkA()
{
_serviceA.DoWork();
}
public void DoWorkB()
{
_serviceB.DoWork();
}
}
```
## Describe the solution you'd like
One solution is to Singleton, so all initialization overhead get mitigated. However, doing so forces us to pass down request-only properties into method where we could store in request-only object and inject into services.
Or we can have a lazy initialization like this
```
[RegisterPerRequest(supportLazyInitialization: true)]
public class ServiceA : IServiceA
{
public void DoWork(int value)
{
// do something for A
}
}
```
```
public class MyService : IMyService
{
private readonly Lazy _serviceA;
private readonly Lazy _serviceB;
public MyService(Lazy serviceA, Lazy serviceB)
{
_serviceA = serviceA;
_serviceB = serviceB;
}
public void DoWork(int value)
{
if (value < 42)
{
_serviceA.Value.DoWork();
}
else
{
_serviceB.Value.DoWork();
}
}
}
```
```
// Registering a type mapping for the lazy proxy.
builder
.Register(c =>
{
var context = c.Resolve();
return LazyProxyBuilder.CreateInstance(
() => context.ResolveNamed(registrationName));
})
.As();
```
## Additional context
- Information is taken from https://dev.to/hypercodeplace/lazy-dependency-injection-37en
- https://github.com/servicetitan/lazy-proxy-autofac
贡献指南
评估
这个 Issue 还没有评估数据。