Created
November 8, 2019 04:00
-
-
Save nkosihenry/26dd2bbf375f10e5e2c6d38d2d17f7b8 to your computer and use it in GitHub Desktop.
Ninject Internal Constructor Demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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