Ninject scoping for DBContext used in Quartz.Net job - ninject

What's the best scoping to use for a DbContext implementation that gets instantiated via Ninject dependency resolver during execution of a Quartz.Net job implementation? If I used thread scope, will the same instance of DbContext get served if the same thread in Quartz's thread pool is used to execute the job multiple times?
I would like a scope that means I get one (and only one) new instance of the DbContext each time the job is fired.

Yes, i would advise against using InThreadScope. When a thread-pool thread is used, there will be leakage.
Furthermore, there's nothing built-in into ninject like a "QuartzScope", so you'll have to create your own solution. let's start with the instantiation of the job. That's covered by this stackoverflow answer and, more extensively, by the source code of this nuget package.
Now one possible solution is to extend the JobFactory to manage the creation of the DbContext and inject it into the job and all its dependencies (as an inherited ConstructorArgument parameter). However, that has two drawbacks: Always creates a DBContext (whether the job needs it or not), and you need to track DBContext instances so you can .Dispose() of them in the IJobFactory.ReturnJob(IJob) method (p.ex. by a Dictionary<IJob, DBContext or the likes).
The much easier way is to use .InCallScope (included in Ninject.Extensions.NamedScope) for the DbContext binding. This will create one DbContext instance per kernel.Get<FooJob>().
If you need to have different scopes for your DbContext - depending on where you use them, p.Ex. inside a Job and inside your ASP.NET MVC stuff, you might want to look at Ninject Conditional Self bind to change scope (For Task-scheduler) not working properly?

Related

Dependency injection - somewhere between constructor and container

I have a situation where i am currently using constructor dependency injection for a small module that fits inside a larger web framework.
Its working fine but now there is a new class being introduced that requires 2 objects passed to it. But, 1 of the objects requires a lot of work to get set up - essentially it invovles around 4 method calls which create other objects in order to get it into a working state ready to be passed to my object.
My dilemna is that constructor injection is no use due to the work involved, but introducing a ioc container is way overboard, especially for this 1 off use case.
So, how should this be handled? Is there some sort of solution that sits in the middle of these two options?
You've effectively got four five choices:
Poor Man's DI (create objects manually and pass to constructors)
IoC container
Factory method
Abstract factory
Builder (thanks, Mark Seemann!)
I usually start off with an IoC container, but I do a lot of DI. (I've seen too many tightly-coupled codebases.)
If you don't want to introduce an IoC container, I'd lean towards Poor Man's DI.
If you're working in any object-oriented language (not just C#), I recommend reading the book Dependency Injection in .NET. It covers the patterns and anti-patterns in detail.
1 of the objects requires a lot of work to get set up - essentially it invovles around 4 method calls which create other objects in order to get it into a working state ready to be passed to my object.
OK, then create the object and pass the completely initialized object to the constructor, in which it needs to go.
Creating that object sounds like a job for a Builder or Factory.
My dilemna is that constructor injection is no use due to the work
involved,
I prefer Constructor Injection and see no reasons to avoid it.
Using modern IoC frameworks you can specify creation logic that involves "a lot of work to get set up" via factory/ factory method.
No matter how many steps are needed to build an instance of IMyService, you can simply use a constructor dependency to inject it.
Castle Windsor
container.AddFacility<FactorySupportFacility>()
.Register(
Component.For<IMyFactory>().ImplementedBy<MyFactory>(),
Component.For<IMyService>()
.UsingFactoryMethod(k => k.Resolve<IMyFactory>().Create())
);
Unity
var container = new UnityContainer();
container.RegisterType<IMyFactory, MyFactory>();
container.RegisterType<IMyService>(
new InjectionFactory(c => c.Resolve<IMyFactory>().Create()));

Antipatterns of IoC container usage. Why IoC containers are so complex and used so "fancy" way?

I'm seriously start thinking that usage of IoC container provokes to create overdesigned solutions (at least it provokes me to try to use various unnecessary features:).
It's the time to synchronize my "IoC" antipatterns list with community one's..
My short experience tell that it is absolutely enough to call Resolve method once per application at startup to resolve some infrastructure singletons and initiate with them "transient object's factory" that could produce new "smaller life time grain factories" . Even to make those factories thread safe (e.g. create one instance per thread) is so easy to achieve by adding 10 code lines into factory... Still those factories are much more simpler then "library's integration with IoC tool". Interception? Just create your own wrappers... Life time managers / dependency strategies/ parent containers? Call the Resolve only once at bootstrapper and you won't think about that.
Could you help me to understand why developers call Resolve several times on different application layers (by passing container or by passing delegate to container) and then have a lot of things to think about? I really worry that I miss something.
Some kind of IoC are anti-patterns or may be in some cases. For example the service locator antipattern. But if you are using constructor injection at the beginning of your application - and only there - then it should not lead to an anti-pattern.
Injecting a DI container interface in a class is a wrong use of constructor injection. If DI is not part of the business logic of your class it should not know or depend on DI container nor should it depend on IKitchen. It's only fine to inject your DI container in some kind of helper or service working in conjunction with your dependency injection container, because it's purpose is to work with or around DI container. The examples in the links you give are misuse of IoC. It does not mean that IoC in general is an anti-pattern.
I think the correct question would be "Can constructor injection be an anti-pattern?". So far I've never faced any situation or seen any example where it was so I would say "no", until I face such a situation.
When it was not clear to me how to use an IoC container, I decided to stop using it, because I thought was just an overcomplication over the simple dependency injection.
It is true though that even without IoC is possible to fall in the over-injection cases.
A while ago I read some posts from the author of ninject that opened my mind.
As you already know the injector should be used only inside the context root. However, in order to avoid over-injections, I decided to introduce an exception of the rule for injected factories.
In my framework, factories (and only factories) can use the injector container. Factories are binded in the container in the context root and therefore can be injected. Factories become valid dependencies and are used to create new objects inside other objects, using the injector container to facilitate dependencies injection.
Read This
Clearly something wrong. New library should not bring additional complex code.
I've found somebody who possibly could understand me :)
Constructor over-injection anti-pattern
Other antipattern in my eyes is pushing the initialization of container "deeper" then actual bootsrapper.
For example Unity and WCF recommendations
Bootstrapper in wcf app is the service constructor, then just put container initialization to constructor. I do not understand reasons to recommend to go for programming wcf sevice behaiviors and custome sevice host factory: if you want to have "IoC container free" bootstrapper - it is absurd, if you need to have "IoC container free" service contract implementation - just create second "IoC container free" service contract implementation.

Is Kernel.Get<T>() threadsafe + good pattern to share the kernel among components

Is Kernel.Get() threadsafe? My goal is share an instance of my kernel among all my componenets and they may all very well call Kernel.Get() at the same time on different threads.
Is Kernel.Get() thread safe?
What is the best pattern to share the application kernel among all application components which are sitting in different dll's? I prefer not to pass an instance of a factory to every component of my application if this makes sense.
Get is threadsafe but creating new kernel instances (ctor) is currently not threadsafe.
Generally you should try to minimize your access to the kernel to an absolute minimum. Accessing the kernel form everywhere is a very bad design and makes your code much less reusable. See Service Locator Antipattern
The only situations where you access the kernel should be:
Once in the composite root of the application (e.g. Program.Main, App.xaml, MVC Controller creation)
Inside a factory if you don't know how many instances you need when the composite root is created
Inside a factory if you don't know which implementation is required when the composite root is created
Inside a factory if you need to create a component late due to memory/resource constraints.
In all cases limit the access to the kernel to the composite root and inject factories (class or Func<T>) to the classes where you need to create objects during runtime. The best way to give those factories access to the kernel is still constructor injection even if you do not prefer doing so. Or use Func<T> ( Does Ninject support Func (auto generated factory)? ).
Yes, it is thread safe; The primary app I work on has a single kernel that serves a large SAAS app. So it gets pounded and it does just fine. We also have a multi-threaded page generator test suite that exposed a thread issue in Ninject last fall, but has been fixed and has been fine since then. So I know for sure that it's ok.
There are lots of different patterns for exposing the kernel. We use a ServiceLocator pattern (basically a static container for the container.)
For the different dll's. We have a NinjectModule in each dll that does it's own bindings and then the app does a assembly scan for NinjectModules at startup when it sets of the ServiceLocator.

Can autofac do partial Resolve?

I seem to need this a lot.
Let's say I have a class with constructor taking several arguments. Some of these can be resolved by registering components. But the rest are instances created during runtime (e.g. fetching an entity from database).
Can Autofac deal with these situations in a nice way? Or is my design sub-optimal?
To clarify, I have classes that have constructors like this:
public MyClass(IService1 service1, IService2 service2, Data1 data1, Data2 data2)
{
//...
}
And I would like to do something like this:
container.Resolve<MyClass>(data1, data2);
You can handle this elegantly by registering a factory method in the Autofac container. You resolve the factory method, and then use it to create instances with your runtime dependencies. You can do this yourself by registering and resolving delegates or custom factory types. However, Autofac has explicit support for delegate factories.
There is not enough information to comment on your design. I'll leave that to you :)
I would say your design is sub optimal.
You seem to be mixing to things. Dependency injection (using a container) should mainly be used for injecting service components into other components. Don't inject thing like entities, because it is not up to the container to manage their lifetime. Rather, inject a service that can manage entities for you, such as a repository. Although topic of discussion, I would neither inject a unit of work, but rather a factory for creating unit of works. This way your application manages the lifetime of the unit of work explicitly.

Implementing repositories using NHibernate and Spring.Net

I'm trying to get to grips with NHibernate, Fluent NHibernate and Spring.
Following domain-driven design principals, I'm writing a standard tiered web application composed of:
a presentation tier (ASP.Net)
a business tier, comprising:
an application tier (basically a set of methods made visible to UI tier)
repository interfaces and domain components (used by the application tier)
A persistence tier (basically the implementation of the repository interfaces defined in the business tier)
I would like help determining a way of instantiating an NHibernate ISession in such a way that it can be shared by multiple repositories over the lifetime of a single request to the business tier. Specifically, I would like to:
allow the ISession instance and any transaction to be controlled outwith the repository implementation (perhaps by some aspect of the IOC framework, an interceptor?)
allow the ISession instance to be available to the repositories in a test-friendly manner (perhaps via injection or trough some shared 'context' abstraction)
avoid any unnecessary transactions being created (i.e. when only read-only operations have been executed)
allow me to write tests that use SQLLite
allow me to use Fluent NHibernate
allow the repository implementation to remain ignorant of the host environment. I don't yet know if the businese tier will run in-process with the presentation tier or will be hosted separately under WCF (in IIS), so I don't want to bind my code too closely to a HTTP context (for example).
My first attempt to solve this problem had been using the Registry pattern; storing the ISession instance in a ThreadStatic property. However, subsequent reading has suggested that isn't the best solution (as ASP.Net can switch the thread within the page lifecycle, I believe).
Any thoughts, part solutions, pattern names, pointers to up-to-date samples (NHibernate 2) will be most gratefully received.
I have not used Spring.NET so I can't comment on that. However, the rest sounds remarkably (or perhaps not so remarkably; we're hardly the first to implement these things ;) similar to my own experience. I too had trouble finding a One True Best Practice so I just read as much as I could and came up with my own interpretation.
In my situation I wanted transaction/session management to be external to the repository as well as keep repository concerns from bubbling up out of them (i.e. the code using the repository should not need to know that it's using NHibernate internally and shouldn't need to know anything about NHibernate session management). In my case it was decided that transactions would be created by default lest developers forget them, so I had to have a read-only escape mechanism. I went with the Unit of Work pattern with the NHibernate ISession instance store inside. Calling code (I also created a DSL interface for the UoW) might look something like:
using (var uow = UoW.Start().ReadOnly().WithHttpContext()
.InNewScope().WithScopeContext(ScopeContextProvider.For<CRMModel>())
{
// Repository access
}
In practice, that could be as short as UoW.Start() depending on how much context is already available. The HttpContext part refers to the storage location for the UoW which is, unsurprisingly, the HttpContext in this case. As you mentioned, for a ASP .NET application, HttpContext is the safest place to store things. ScopeContextProvider basically makes sure the right data context is provided for the UoW (ISession instance to the appropriate database/server, other settings). The "ScopeContext" concept also makes it easy to insert a "test" scope context.
Going this route makes the repositories explicitly dependent on the UoW interface. Actually, you might be able to abstract it some but I'm not sure I see the benefit. What I mean is, each repository method retrieves the current UoW instance and then pulls out the ISession object (or simply a SqlConnection for those methods that don't use NHibernate) to run the NHibernate query/operation. This works for me though because it also seems like the ideal time to make sure that the current UoW is not read-only for methods that might need to run CRUD.
Overall, I think this is one approach that solves all your points:
Allows session management to be external to the repository
ISession context can be mocked or pointed at a context provider for a test environment
Avoids unnecessary transactions (well, you'd have to invert what I did and have a .Transactional() call or something)
I can't see why you couldn't test with SQLite since that's more of an NHibernate concern
I use Fluent NHibernate myself
Allows the repository to be ignorant of the host environment (that is, the repository caller controls the UoW storage context)
As for the UoW implementation, I'm partially kicking myself for not looking around more before I started. There's a project called machine.uow which I understand is fairly popular and works well with NHibernate. I haven't played with it much so I can't say if it solves all my requirements as neatly as the one I wrote myself, but it might have saved development time as well.
Perhaps we'll get some comments as to where I went wrong or how to improve things, but I hope this is at least helpful in some way.
For reference, the software stack I'm using is:
ASP.NET MVC
Fluent NHibernate on top of NHibernate
Ninject for dependency injection
What you are describing is supported by the Spring.NET framework almost out of the box. Only for FluentNHibernate you need to add a custom SessionFactory (not a lot of code, look here:Using Fluent NHibernate in Spring.NET) to Spring.NET.
Every repository can use the same ISession, just inject the SessionFactory in your repositories and use Spring.NET's transaction services.
Just try it out, they have pretty thorough documentation imho.