Skip to content

Instantly share code, notes, and snippets.

@nkosihenry
Created November 8, 2019 04:00
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 nkosihenry/26dd2bbf375f10e5e2c6d38d2d17f7b8 to your computer and use it in GitHub Desktop.
Save nkosihenry/26dd2bbf375f10e5e2c6d38d2d17f7b8 to your computer and use it in GitHub Desktop.
Ninject Internal Constructor Demo
using Ninject.Activation;
using System;
using System.Reflection;
namespace Ninject.Demo.Infrastructure {
public class MyProvider : IProvider {
public Type Type => typeof(Persisrer<>);
public object Create(IContext context) {
var genericArguments = context.GenericArguments;
var genericType = this.Type.MakeGenericType(genericArguments); //Persister<T>
var argTypes = new[] {
typeof(IDependency)
};
// Get the constructor that take provided arguments
var constructor = genericType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, argTypes, null);
var parameters = new object[] {
new Dependency()
};
return constructor.Invoke(parameters);
}
}
public interface IPersist<TEntity> {
void Persist(TEntity entity);
}
internal interface IDependency {
}
internal class Dependency : IDependency {
public Dependency() {
}
}
public class Persisrer<T> : IPersist<T> {
private object dependency;
internal Persisrer(IDependency dependency) {
this.dependency = dependency;
}
public void Persist(T entity) {
throw new NotImplementedException();
}
}
}
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Ninject;
using Ninject.Demo.Infrastructure;
namespace UnitTestProject.tests {
[TestClass]
public class UnitTest8 {
[TestMethod]
public void TestMethod1() {
//Arrange
var kernel = new StandardKernel();
kernel.Bind(typeof(IPersist<>)).ToProvider(typeof(MyProvider));
var actual = kernel.Get<IPersist<dummy>>();
Assert.IsNotNull(actual);
}
public class dummy { }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment