Ninject fails to resolve interface type when the concrete type derives from an abstract base class - compact-framework

I have a problem with Ninject trying to resolve an interface type where the concrete type derives from an abstract base class that implements the interface.
EDIT: This is on Windows Mobile using .NET CF.
My particular issue involves presenters and views, so I stick to that in this example instead of foos and bars.
I want to inject factories for presenters and views to allow for late creation of those instances deep down the UI view stack.
Below I've omitted all error checking for better readability.
My factory interface:
public interface IFactory<T>
{
T Create();
}
My presenter and view:
public sealed class Presenter
{
private readonly View view;
public Presenter(View view)
{
this.view = view;
}
}
public sealed class View
{
public View()
{
}
}
First, I'll show what works perfectly, that Ninject resolves as expected. This will not include the abstract base class I mentioned at the beginning. After this, I'll add the slight modifications with the abstract base class that will make Ninject throw when trying to resolve the dependencies.
We see above that the presenter depends on the view, so the presenter factory will depend on the view factory:
public sealed class GoodPresenterFactory : IFactory<Presenter>
{
private readonly IFactory<View> viewFactory;
public GoodPresenterFactory(IFactory<View> viewFactory)
{
this.viewFactory = viewFactory;
}
public Presenter Create()
{
return new Presenter(this.viewFactory.Create());
}
}
public sealed class ViewFactory : IFactory<View>
{
public ViewFactory()
{
}
public View Create()
{
return new View();
}
}
Wiring this up with Ninject:
Bind<IFactory<Presenter>>().To<GoodPresenterFactory>();
Bind<IFactory<View>>().To<ViewFactory>();
And then resolving the presenter factory:
var presenterFactory = container.Get<IFactory<Presenter>>();
Everything up until now works perfectly. The dependency on the view factory inside the presenter factory is resolved as expected.
Now, I have a million classes that looks like GoodPresenterFactory above and I therefore wanted a small base class to handle some trivial common stuff, like the dependency on the view factory in the presenter factory:
public abstract class FactoryBase<T, U> : IFactory<T>
{
protected readonly U dependency;
protected FactoryBase(U dependency)
{
this.dependency = dependency;
}
public abstract T Create();
}
Then the presenter factory will change and something in that change will make Ninject fail resolving:
public sealed class BadPresenterFactory : FactoryBase<Presenter, IFactory<View>>
{
public BadPresenterFactory(IFactory<View> viewFactory)
: base(viewFactory)
{
}
public override Presenter Create()
{
return new Presenter(this.dependency.Create());
}
}
And changing the Ninject wiring accordingly:
Bind<IFactory<Presenter>>().To<BadPresenterFactory>();
Bind<IFactory<View>>().To<ViewFactory>();
Those changes will make Ninject throw an ArgumentNullException when doing
var presenterFactory = container.Get<IFactory<Presenter>>();
Call stack from the exception:
at System.Reflection.RuntimeMethodInfo.GetParentDefinition()
at System.Reflection.CustomAttribute.IsDefined(MemberInfo member, Type caType, Boolean inherit)
at System.Reflection.RuntimeMethodInfo.IsDefined(Type attributeType, Boolean inherit)
at System.Attribute.IsDefined(MemberInfo element, Type attributeType, Boolean inherit)
at System.Attribute.IsDefined(MemberInfo element, Type attributeType)
at Ninject.Infrastructure.Language.ExtensionsForMemberInfo.HasAttribute(MemberInfo member, Type type)
at Ninject.Selection.Heuristics.StandardInjectionHeuristic.ShouldInject(MemberInfo member)
at Ninject.Selection.Selector.<>c__DisplayClassa.<SelectMethodsForInjection>b__9(IInjectionHeuristic h)
at System.Linq.Enumerable.Any[TSource](IEnumerable`1 source, Func`2 predicate)
at Ninject.Selection.Selector.<SelectMethodsForInjection>b__8(MethodInfo m)
at System.Linq.Enumerable.<WhereIterator>d__0`1.MoveNext()
at Ninject.Planning.Strategies.MethodReflectionStrategy.Execute(IPlan plan)
at Ninject.Planning.Planner.<>c__DisplayClass2.<GetPlan>b__0(IPlanningStrategy s)
at Ninject.Infrastructure.Language.ExtensionsForIEnumerableOfT.Map[T](IEnumerable`1 series, Action`1 action)
at Ninject.Planning.Planner.GetPlan(Type type)
at Ninject.Activation.Providers.StandardProvider.Create(IContext context)
at Ninject.Activation.Context.Resolve()
at Ninject.KernelBase.<Resolve>b__4(IContext context)
at System.Linq.Enumerable.<SelectIterator>d__d`2.MoveNext()
at System.Linq.Enumerable.<CastIterator>d__b0`1.MoveNext()
at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source)
at Ninject.ResolutionExtensions.Get[T](IResolutionRoot root, IParameter[] parameters)
at NinjectTest.Program.Main()
If I modify FactoryBase so that it has no dependency, it's just a naked base class, then Ninject also fails.
public abstract class NakedFactoryBase<T> : IFactory<T>
{
protected NakedFactoryBase()
{
}
public abstract T Create();
}
public sealed class PointlessPresenterFactory : NakedFactoryBase<Presenter>
{
private readonly IFactory<View> viewFactory;
public PointlessPresenterFactory(IFactory<View> viewFactory)
{
this.viewFactory = viewFactory;
}
public override Presenter Create()
{
return new Presenter(this.viewFactory.Create());
}
}
As you can see, that failing PointlessPresenterFactory is identical to the succeeding GoodPresenterFactory, apart from the direct IFactory<Presenter> implementation in GoodPresenterFactory, as opposed to the completeley naked base class used in PointlessPresenterFactory.
Any idea why Ninject fails to resolve when the factory base class is used?

This issue has been fixed in build 2.3.0.46 and will be part of the next release (2.4).
NOTE: because CF seems not to allow to detect is a method is generic or not the Inject attribute can not be defined on base methods anymore. It has to be defined on the overload method.

Related

Inject DbContextOptions vs DbContext in a repository EF Core

I have the StudentDbContext
public class StudentDbContext : DbContext
{
public StudentDbContext()
{
}
public StudentDbContext(DbContextOptions<StudentDbContext> options)
: base(options)
{
}
public virtual DbSet<Students> Students{ get; set; }
}
and then I have a repository and I try to understand what is the difference if I inject the StudentDbContext vs inject DbContextOptions
Inject the DbContextOptions
class StudentRepository : IStudentRepository
{
private readonly DbContextOptions<StudentDbContext> _context;
public StudentRepository(DbContextOptions<StudentDbContext> context)
{
_context = context;
}
}
Inject StudentDbContext
class StudentRepository : IStudentRepository
{
private readonly StudentDbContext _context;
public StudentRepository(StudentDbContext context)
{
_context = context;
}
}
Are there any advantages or disadvantages in each case?
DbContextOptions class is used to create the options to be used by a DbContext. It configures the database (and other options) to be used for the database context. DbContext class contains DbSet properties for each entity in the model.
If you try to use DbContextOptions in a repository you will have no access to any model since it doesn't have them.
DbContextOptions and DbContextOptions<TContext> have different use cases.
You need to inject DbContextOptions (generic or not) in subtypes of DbContext.
The DbContextOptions instance will contain the options that you have configured in the Startup class:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContextFactory<ConcreateDbContext>(
options => options.UseSqlServer(#"Server=(localdb)\mssqllocaldb;Database=Test")
);
}
If your DbContext implementation is not supposed to be inherited from, you will inject in your ConcreateDbContext the generic version of options type DbContextOptions<ConcreateDbContext>, and this ensures that the correct options for the specific DbContext subtype are resolved from dependency injection. You can also, mark your ConcreateDbContext as sealed, as the class is not designed to be inherited from.
public sealed class ConcreateDbContext: DbContext
{
public ConcreateDbContext(DbContextOptions<ConcreateDbContext> contextOptions)
: base(contextOptions)
{
}
}
In case that you want to have a DbContext that is intended to be inherited from, you are supposed to expose a protected constructor which will take as a parameter the non-generic version of DbContextOptions.
public class BaseDbContext: DbContext
{
protected BaseDbContext(DbContextOptions contextOptions)
: base(contextOptions)
{
}
}
In case you want to have a DbContext that is intended to be both instantiated and inherited from, you will have two constructors, one taking the generic, and one the non-generic version of DbContextOptions.
And when you want to interact with the data in your database, you will inject the concrete DbContext implementation (in your case StudentDbContext).

How can I get HttpContext inside an abstract class in ASPNETCore

I have the following Repository:
public class TestRepository : WebCaller<Data>, ITestRepository
{
string connString = this.GetConnectionString();
.... some code here
}
In my Repository I can do Dependency Injection to the constructor without a problem.
In my abstract class WebCaller I need to get access to HttpContext somehow, I was reading that you can Inject IHttpContextAccessor to get access to the context, but because this is an Abstract class, that also lives outside the Web project, I can't have a constructor.
I was trying to do this:
public abstract class WebCaller<T> : WebRequest, IDisposable
{
//[Inject]
public ITestRepository TestRepo
{
get
{
return this.HttpContext.RequestServices.GetRequiredService<ITestRepository >();
}
}
..... more code here
}
Was trying to use Inject attribute but was reading that is no longer available, so should be other way to pass HttContext to the abstract class.
You can have a constructor on your abstract class. Just inject IHttpContextAccessor to it. Then any derived class will also take IHttpContextAccessor and pass it to its base constructor (your abstract class constructor). You can make the abstract class constructor protected.
Like:
public abstract class WebCaller<T> : WebRequest, IDisposable
{
protected WebCaller(IHttpContextAccessor contextAccessor)
{
}
}
public class TestRepository : WebCaller<Data>, ITestRepository
{
public TestRepository(IHttpContextAccessor contextAccessor) : base(contextAccessor)
{
}
string connString = this.GetConnectionString();
.... some code here
}

Castle windsor wire generic irepository with 2 types

Hi I am trying to change a code example found here
http://imar.spaanjaars.com/577/aspnet-n-layered-applications-implementing-a-repository-using-ef-code-first-part-5
In his example he uses structure map, when I converted it to windsor I can get it to work with the one repository using the following.
container.Register(Component.For<IUnitOfWorkFactory>().ImplementedBy<EFUnitOfWorkFactory>(),
Component.For<IUnitOfWork>().ImplementedBy<EFUnitOfWork>(),
Component.For<Model.Repositories.IPeopleRepository>().ImplementedBy<PeopleRepository>().LifestyleTransient());
But what I really want to do is to map all the irepository based interfacees to thier implementation.
Here is the IRepository, T is the entity, K is the prmiary key type
public interface IRepository<T, K> where T : class
{
}
Its implementation Is
public abstract class Repository<T> : IRepository<T, int>, IDisposable where T : DomainEntity<int>
{
}
My controller has the interface IPeopleRepository as a constructor paramerter.
public interface IPeopleRepository : IRepository<Person, int>
{
}
public class PeopleRepository : Repository<Person>, IPeopleRepository
{
}
I want to have one register to register all repositories, something like this, but it wont match and i get the error Service 'Spaanjaars.ContactManager45.Model.Repositories.IPeopleRepository' which was not registered
container.Register(Component.For(typeof(IRepository<,>))
.ImplementedBy(typeof(Repository<>))
.LifestylePerWebRequest());
What am i missing in regards to this? is it because my irepository has 2 generic types?
In order to map all the IRepository based interfaces to their implementations .WithService.AllInterfaces() should be used.
This registration should solve your issue.
container.Register(
Classes.FromThisAssembly()
.BasedOn(typeof(IRepository<,>))
.WithService.AllInterfaces()
.LifestylePerWebRequest());
There are some tests to test it. I claim they are green.
[TestClass]
public class InstallerTest
{
private IWindsorContainer container;
[TestInitialize]
public void Init()
{
container = new WindsorContainer().Install(new Installer());
}
[TestMethod]
public void ResilveTest_ResolvesViaIRepository()
{
// act
var repository = container.Resolve<IRepository<Person, int>>();
// assert
repository.Should().BeOfType<PeopleRepository>();
}
[TestMethod]
public void ResilveTest_ResolvesViaIPeopleRepository()
{
// act
var repository = container.Resolve<IPeopleRepository>();
// assert
repository.Should().BeOfType<PeopleRepository>();
}
}
public class Installer : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(
Classes.FromThisAssembly()
.BasedOn(typeof(IRepository<,>))
.WithService.AllInterfaces()
.LifestylePerThread());
}
}

design pattern query

i have a question regarding design patterns.
suppose i want to design pig killing factory
so the ways will be
1) catch pig
2)clean pig
3) kill pig
now since these pigs are supplied to me by a truck driver
now if want to design an application how should i proceed
what i have done is
public class killer{
private Pig pig ;
public void catchPig(){ //do something };
public void cleanPig(){ };
public void killPig(){};
}
now iam thing since i know that the steps will be called in catchPig--->cleanPig---->KillPig manner so i should have an abstract class containing these methods and an execute method calling all these 3 methods.
but i can not have instance of abstract class so i am confused how to implement this.
remenber i have to execute this process for all the pigs that comes in truck.
so my question is what design should i select and which design pattern is best to solve such problems .
I would suggest a different approach than what was suggested here before.
I would do something like this:
public abstract class Killer {
protected Pig pig;
protected abstract void catchPig();
protected abstract void cleanPig();
protected abstract void killPig();
public void executeKillPig {
catchPig();
cleanPig();
killPig();
}
}
Each kill will extend Killer class and will have to implement the abstract methods. The executeKillPig() is the same for every sub-class and will always be performed in the order you wanted catch->clean->kill. The abstract methods are protected because they're the inner implementation of the public executeKillPig.
This extends Avi's answer and addresses the comments.
The points of the code:
abstract base class to emphasize IS A relationships
Template pattern to ensure the steps are in the right order
Strategy Pattern - an abstract class is as much a interface (little "i") as much as a Interface (capital "I") is.
Extend the base and not use an interface.
No coupling of concrete classes. Coupling is not an issue of abstract vs interface but rather good design.
public abstract Animal {
public abstract bool Escape(){}
public abstract string SaySomething(){}
}
public Wabbit : Animal {
public override bool Escape() {//wabbit hopping frantically }
public override string SaySomething() { return #"What's Up Doc?"; }
}
public abstract class Killer {
protected Animal food;
protected abstract void Catch(){}
protected abstract void Kill(){}
protected abstract void Clean(){}
protected abstract string Lure(){}
// this method defines the process: the methods and the order of
// those calls. Exactly how to do each individual step is left up to sub classes.
// Even if you define a "PigKiller" interface we need this method
// ** in the base class ** to make sure all Killer's do it right.
// This method is the template (pattern) for subclasses.
protected void FeedTheFamily(Animal somethingTasty) {
food = somethingTasty;
Catch();
Kill();
Clean();
}
}
public class WabbitHunter : Killer {
protected override Catch() { //wabbit catching technique }
protected override Kill() { //wabbit killing technique }
protected override Clean() { //wabbit cleaning technique }
protected override Lure() { return "Come here you wascuhwy wabbit!"; }
}
// client code ********************
public class AHuntingWeWillGo {
Killer hunter;
Animal prey;
public AHuntingWeWillGo (Killer aHunter, Animal aAnimal) {
hunter = aHunter;
prey = aAnimal;
}
public void Hunt() {
if ( !prey.Escape() ) hunter.FeedTheFamily(prey)
}
}
public static void main () {
// look, ma! no coupling. Because we pass in our objects vice
// new them up inside the using classes
Killer ElmerFudd = new WabbitHunter();
Animal BugsBunny = new Wabbit();
AHuntingWeWillGo safari = new AHuntingWeWillGo( ElmerFudd, BugsBunny );
safari.Hunt();
}
The problem you are facing refer to part of OOP called polymorphism
Instead of abstract class i will be using a interface, the difference between interface an abstract class is that interface have only method descriptors, a abstract class can have also method with implementation.
public interface InterfaceOfPigKiller {
void catchPig();
void cleanPig();
void killPig();
}
In the abstract class we implement two of three available methods, because we assume that those operation are common for every future type that will inherit form our class.
public abstract class AbstractPigKiller implements InterfaceOfPigKiller{
private Ping pig;
public void catchPig() {
//the logic of catching pigs.
}
public void cleanPig() {
// the logic of pig cleaning.
}
}
Now we will create two new classes:
AnimalKiller - The person responsible for pig death.
AnimalSaver - The person responsible for pig release.
public class AnimalKiller extends AbstractPigKiller {
public void killPig() {
// The killing operation
}
}
public class AnimalSaver extends AbstractPigKiller {
public void killPing() {
// The operation that will make pig free
}
}
As we have our structure lets see how it will work.
First the method that will execute the sequence:
public void doTheRequiredOperation(InterfaceOfPigKiller killer) {
killer.catchPig();
killer.cleanPig();
killer.killPig();
}
As we see in the parameter we do not use class AnimalKiller or AnimalSever. Instead of that we have the interface. Thank to this operation we can operate on any class that implement used interface.
Example 1:
public void test() {
AnimalKiller aKiller = new AnimalKiller();// We create new instance of class AnimalKiller and assign to variable aKiller with is type of `AnimalKilleraKiller `
AnimalSaver aSaver = new AnimalSaver(); //
doTheRequiredOperation(aKiller);
doTheRequiredOperation(aSaver);
}
Example 2:
public void test() {
InterfaceOfPigKiller aKiller = new AnimalKiller();// We create new instance of class AnimalKiller and assign to variable aKiller with is type of `InterfaceOfPigKiller `
InterfaceOfPigKiller aSaver = new AnimalSaver(); //
doTheRequiredOperation(aKiller);
doTheRequiredOperation(aSaver);
}
The code example 1 and 2 are equally in scope of method doTheRequiredOperation. The difference is that in we assign once type to type and in the second we assign type to interface.
Conclusion
We can not create new object of abstract class or interface but we can assign object to interface or class type.

Injecting my UnitOfWork into my Repository Constructor

Im very new but on a quest to learn nhibernate and DI with structuremap so am making an app to test everything out.
I am having some problems injecting my unitofwork into my base repository. I create a unitofwork on every request then either commit or rollback at the end. But when tryin to inject into my base repository its always null when i go to use it in my methods. More specifically i get this error: "Object reference not set to an instance of an object". Any ideas what im doing wrong and if this is the correct route i should be going?
Many thanks in advance.
Base Repository:
public abstract class Repository<T> : IRepository<T>
{
public readonly IUnitOfWork _unitOfWork;
public Repository(IUnitOfWork UnitOfWork)
{
UnitOfWork = _unitOfWork;
}
public Repository() {}
public void Save(T obj)
{
_unitOfWork.CurrentSession.Save(obj);
}
}
StructureMap registry thats set in my application_start:
public class NHibernateRegistry : Registry
{
public NHibernateRegistry()
{
For<IUnitOfWork>().HybridHttpOrThreadLocalScoped().Use<UnitOfWork>();
For<ISession>().HybridHttpOrThreadLocalScoped().Use(context => context.GetInstance<ISessionFactory>().OpenSession());
For<ISessionFactory>().Singleton().Use(NHibernateSessionFactory.GetSessionFactory());
}
}
Update:
The baserepository is inherited by specific repositorys ie ArticleRepository then im injecting that into my aspx pages on application_start. Then my aspx page inherits a basepage where the buildUp takes place. And i access the repository like this:
public IArticleRepository ArticleRepo { get; set; }
public void SaveThing()
{
ArticleRepo.Save(object);
}
This gets called on application_start:
public class Bootstrapper
{
public static void BootStrap()
{
ObjectFactory.Configure(x =>
{
x.AddRegistry<NHibernateRegistry>();
x.AddRegistry<WebRegistry>();
});
}
}
And in the webregistry:
For<IArticleRepository>().Use<ArticleRepository>();
There is a good chance your ArticleRepository doesn't have a constructor that takes an IUnitOfWork as a parameter make sure you have the following
public class ArticleRepository : Repository<Article>
{
public ArticleRepository(IUnitOfWork unitOfWork) : base(unitOfWork)
{
}
...
}
Remember Strcuture map uses the greediest constructor on the class that it instantiates. Since your abstract repository class will never be instantiated it will not use its constructors. I would also suggest not having any default constructors if your classes need to have their dependencies injected that way. Less chance for errors that way.
public readonly IUnitOfWork _unitOfWork;
public Repository(IUnitOfWork UnitOfWork)
{
UnitOfWork = _unitOfWork;
}
I think you mean to write
public readonly IUnitOfWork _unitOfWork;
public Repository(IUnitOfWork UnitOfWork)
{
_unitOfWork = UnitOfWork;
}
You were assigning the local variable to the parameter instead of the parameter to the local variable.
Edit: Also you should write your parameter with a lowercase U 'unitOfWork' instead of 'UnitOfWork'