依赖注入 C# 每次都获取可枚举的新实例
我有一个实现接口的类列表,如下所示:
pulic interface ISample
{
public int Id { get; set; }
}
pulic class SampleA : ISample {}
pulic class SampleB : ISample {}
pulic class SampleC : ISample {}
这些类的生命周期是瞬态的。 我为创建的实例创建一个包装器,如下所示:
public class Wrapper
{
private IEnumerable<ISample> _Samples;
public Wrapper(IEnumerable<ISample> Samples)
{
_Samples = Samples;
}
public void InstanceGenerator(int Id)
{
ISample MySample = _Samples.FirstOrDefault(s => s.Id == Id);
//do somethings...
}
}
包装器类的生命周期是单例的。我希望每次调用“InstanceGenerator”时,它都会创建一个新实例,但它只创建一个实例,并且每次都会返回该实例。
I have a list of class that implement an interface, like this:
pulic interface ISample
{
public int Id { get; set; }
}
pulic class SampleA : ISample {}
pulic class SampleB : ISample {}
pulic class SampleC : ISample {}
Life time of these classs are Transient.
I create a wrapper for created instances, like this:
public class Wrapper
{
private IEnumerable<ISample> _Samples;
public Wrapper(IEnumerable<ISample> Samples)
{
_Samples = Samples;
}
public void InstanceGenerator(int Id)
{
ISample MySample = _Samples.FirstOrDefault(s => s.Id == Id);
//do somethings...
}
}
Life time of Wrapper class is singleton. I would like that every time that I call "InstanceGenerator", it creates a new instance but it only creates one instance and every time returns that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要创建一个工厂来在方法调用中创建新实例,而不是直接注册类型。
以下示例基于您的代码,但也显示了一些差异。除了 ISample 实现和包装器之外,还在 DI 容器中注册了一个工厂。它定义了一个
GenerateSamples
方法,该方法在调用时使用服务提供程序创建新实例:如果运行该示例,您可以检查
InstanceId
来验证是否使用了新实例每次都在InstanceGenerator
方法中。Instead of registering the types directly, you'd need to create a factory that creates new instances in a method call.
The following sample is based on your code, but also shows some differences. In addition to the ISample implementations and the wrapper, a factory is registered in the DI container. It defines a
GenerateSamples
method that uses the service provider to create new instances when called:If you run the sample, you can check the
InstanceId
to verify that a new instance is used in theInstanceGenerator
method every time.