Skip to content

Instantly share code, notes, and snippets.

@akimboyko
Created January 21, 2013 16:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akimboyko/4587186 to your computer and use it in GitHub Desktop.
Save akimboyko/4587186 to your computer and use it in GitHub Desktop.
Ninject post-poned dependency initialization: factory, lazy loading, combination
void Main()
{
var kernel = new StandardKernel();
kernel.Load<FuncModule>(); // for sake of LinqPAD
kernel.Bind<IDependencyFactory>().ToFactory();
// wire concreet implementation of
kernel
.Bind<IDependency>()
.To<DependencyImpl1>()
.NamedLikeFactoryMethod((IDependencyFactory f) => f.GetJob());
kernel
.Bind<Lazy<IDependency>>()
.To<Lazy<IDependency>>()
.NamedLikeFactoryMethod((IDependencyFactory f) => f.GetLazyJob());
kernel
.Bind(typeof (Lazy<>))
.ToMethod(context =>
((ILazyLoader) Activator.CreateInstance(typeof (LazyLoader<>).MakeGenericType(context.GenericArguments),
new object[] { context.Kernel })).Loader);
var abstractFactory = kernel.Get<IDependencyFactory>();
var dependencyUsingFactory = abstractFactory.GetJob();
var lazyDependencyUsingFactory = abstractFactory.GetLazyJob();
dependencyUsingFactory.Dump();
lazyDependencyUsingFactory.Dump();
lazyDependencyUsingFactory.Value.Dump();
var lazyDependency = kernel.Get<Lazy<IDependency>>();
lazyDependency.Dump();
lazyDependency.Value.Dump();
}
public abstract class IDependency { }
public class DependencyImpl1 : IDependency { }
public class DependencyImpl2 : IDependency { }
public interface IDependencyFactory
{
IDependency GetJob();
Lazy<IDependency> GetLazyJob();
}
public interface ILazyLoader
{
object Loader { get; }
}
public class LazyLoader<T> : ILazyLoader
{
private readonly IKernel _kernel;
private static readonly Func<IKernel, Lazy<T>> _lazyLoader = k => new Lazy<T>(() => k.Get<T>());
public LazyLoader(IKernel kernel)
{
if (kernel == null)
throw new ArgumentNullException("kernel");
_kernel = kernel;
}
public object Loader { get { return _lazyLoader(_kernel); } }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment