我需要能够使用 DryIoc 来创建 Lazy 对象。
因为我正在使用一个使用 God 对象并依赖于复杂 Dictionary 的遗留应用程序KeyPair<string, SomeAbstractType>
,所以我想用Lazy<SomeAbstractType>
对应的值替换每个值并让应用程序加载速度更快。
我已经以这种方式完成了 POCO,但由于我远未掌握 DryIoc,因此我可能做得过火了。
这是我希望您能够阅读的代码。
using System;
using System.Diagnostics;
using DryIoc;
namespace ConsoleApplication2
{
public class Program
{
public class Postoned
{
private readonly IContainer _container;
public Postoned(IContainer container)
{
_container = container;
}
public Lazy<T> Create<T>()
{
return new Lazy<T>(() =>
{
Debugger.Break();
return _container.Resolve<T>();
});
}
}
public class Holder
{
public Lazy<int> Li { get; set; }
public Lazy<string> Ls { get; set; }
public Holder(Lazy<int> li, Lazy<string> ls)
{
Li = li;
Ls = ls;
}
}
static void Main(string[] args)
{
var c = new Container();
c.RegisterInstance(c);
c.RegisterMapping<IContainer, Container>();
c.RegisterInstance(66, Reuse.Singleton);
c.RegisterInstance("string 66", Reuse.Singleton);
c.Register(Made.Of(() => new Postoned(Arg.Of<IContainer>())), Reuse.Singleton);
c.Register(Made.Of(r => ServiceInfo.Of<Postoned>(), (Postoned postoned) => postoned.Create<int>()), Reuse.Singleton);
c.Register(Made.Of(r => ServiceInfo.Of<Postoned>(), (Postoned postoned) => postoned.Create<string>()), Reuse.Singleton);
c.Register(Made.Of(() => new Holder(Arg.Of<Lazy<int>>(), Arg.Of<Lazy<string>>())), Reuse.Singleton);
var holder = c.Resolve<Holder>();
Debugger.Break();
var li = holder.Li;
Debugger.Break();
var i = li.Value;
Console.WriteLine(i);
Console.WriteLine(holder.Ls.Value);
Console.ReadLine();
}
}
}
编辑[答案]:
它可以以更简单的方式实现 XD。
using System;
using System.Diagnostics;
using DryIoc;
namespace ConsoleApplication2
{
public class Program
{
public class Holder
{
public Lazy<int> Li { get; set; }
public Lazy<string> Ls { get; set; }
public Holder(Lazy<int> li, Lazy<string> ls)
{
Li = li;
Ls = ls;
}
}
static void Main(string[] args)
{
var c = new Container();
c.RegisterInstance(c);
c.RegisterMapping<IContainer, Container>();
c.RegisterInstance(66, Reuse.Singleton);
c.RegisterInstance("string 66", Reuse.Singleton);
c.Register(Made.Of(() => new Holder(Arg.Of<Lazy<int>>(), Arg.Of<Lazy<string>>())), Reuse.Singleton);
var holder = c.Resolve<Holder>();
Debugger.Break();
var li = holder.Li;
Debugger.Break();
var i = li.Value;
Console.WriteLine(i);
Console.WriteLine(holder.Ls.Value);
Console.ReadLine();
}
}
}