gpt4 book ai didi

generics - DryIoC 将参数传递给基于泛型类型参数的开放泛型服务的构造函数

转载 作者:行者123 更新时间:2023-12-04 08:25:46 25 4
gpt4 key购买 nike

假设我有这项服务和两种策略:

public class SomeService<TEntity> : ISomeService<TEntity>
{
public SomeService(ICurrentDbContext context, IStrategy<TEntity>? delete = null)
: base(context, delete ?? new DefaultStrategy<TEntity>())
{}
}

public class DefaultStrategy<TEntity> : IStrategy<TEntity> {}

public class CustomStrategy<TEntity> : IStrategy<TEntity> {}
我当前的服务注册如下所示:
container.Register(typeof(ISomeService<>), typeof(SomeService<>), Reuse.Transient);
我想在这里实现的是,如果泛型类型参数 T 实现了某个接口(interface),例如 IFoo,则在 ISomeService 的解析尝试上传递 CustomStrategy。否则,将其保留为默认值为 null 的参数。
在这两种情况下,Ofc 的第一个参数都应自动解析为已注册的依赖项。
现在不知道该怎么做,我应该使用拦截器吗?

最佳答案

您可以这样做(但从您的问题中不清楚为什么您有两种策略 DefaultStrategy<TEntity>CustomStrategy<TEntity> )。

using System.Linq;
using NUnit.Framework;

namespace DryIoc.IssuesTests
{
[TestFixture]
public class SO_DryIoC_pass_param_to_constructor_of_open_generic_service_based_on_generic_type_parameter
{
[Test]
public void Test()
{
var container = new Container();

container.Register(typeof(ISomeService<>), typeof(SomeService<>), Reuse.Transient,
made: Parameters.Of.Details((req, p) =>
p.ParameterType.GetGenericDefinitionOrNull() == typeof(IStrategy<>) &&
p.ParameterType.GetGenericParamsAndArgs().Any(x => x.IsAssignableTo<IFoo>())
? null // the default injection behavior
: ServiceDetails.Of(value: null)) // otherwise return the `null` value
);

container.Register<ICurrentDbContext, MyDbContext>();
container.Register(typeof(IStrategy<>), typeof(DefaultStrategy<>));

var s1 = container.Resolve<ISomeService<OtherEntity>>();
Assert.IsNull(((SomeService<OtherEntity>)s1).Delete);

var s2 = container.Resolve<ISomeService<FooEntity>>();
Assert.IsNotNull(((SomeService<FooEntity>)s2).Delete);
}

public interface ISomeService<TEntity> {}
public class SomeService<TEntity> : ISomeService<TEntity>
{
public readonly IStrategy<TEntity> Delete;
public SomeService(ICurrentDbContext context, IStrategy<TEntity> delete = null) => Delete = delete;
}

public interface IFoo {}
public class FooEntity : IFoo {}

public class OtherEntity {}

public interface IStrategy<TEntity> {}
public class DefaultStrategy<TEntity> : IStrategy<TEntity> { }
public class CustomStrategy<TEntity> : IStrategy<TEntity> { }

public interface ICurrentDbContext {}
public class MyDbContext : ICurrentDbContext {}
}
}

关于generics - DryIoC 将参数传递给基于泛型类型参数的开放泛型服务的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65272929/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com