Convention Based Dependency Injection with Ninject 3.0.0 - dependency-injection

I have two projects in my solution... a domain project and MVC3 web project (e.g. MyApp.Domain and MyApp.Web). Previously, when using Ninject.Extensions.Conventions ver. 2, I was able to use the following statement in the NinjectMVC3.cs file, and required dependencies throughout my solution (both web and domain) were injected properly (e.g. IFoo automatically bound to Foo).
kernel.Scan(x =>
{
x.FromAssembliesMatching("*");
x.BindWith<DefaultBindingGenerator>();
});
I have just upgraded to Ninject 3.0.0 (pre-release) and Ninject.Extensions.Conventions 3.0.0 (another pre-release) but the syntax for convention based binding has changed. I have figured out that I can use the following statement with the new version, but it only automatically binds the convention based interfaces in MyApp.Web and not in MyApp.Domain. The previous version bound interfaces throughout the application.
kernel.Bind(x => x
.FromThisAssembly()
.SelectAllClasses()
.BindToAllInterfaces());
Any clue how I can configure convention based binding with the new Ninject version? I assume it has to do with specifying the assembly, but I have tried using FromAssembliesMatching("*") and it fails for everything then.
-- Edit to show my exisiting code in RegisterServices method: --
private static void RegisterServices(IKernel kernel)
{
// This code used to work with v.2 of Ninject.Extensions.Conventions
// kernel.Scan(x =>
// {
// x.FromAssembliesMatching("*");
// x.BindWith<DefaultBindingGenerator>();
// });
// This is the new v3 code that automatically injects dependencies but only for interfaces in MyApp.Web, not MyApp.Domain
kernel.Bind(x => x.FromThisAssembly().SelectAllClasses().BindToAllInterfaces());
// I tried this code, but it throws "Error activating IDependencyResolver" at "bootstrapper.Initialize(CreateKernel)"
// kernel.Bind(x => x.FromAssembliesInPath(AppDomain.CurrentDomain.RelativeSearchPath).SelectAllClasses().BindToAllInterfaces());
// These are dependencies in MyApp.Web that ARE being bound properly by the current configuration
// kernel.Bind<IMemberQueries>().To<MemberQueries>();
// kernel.Bind<IGrantApplicationQueries>().To<GrantApplicationQueries>();
// kernel.Bind<IMailController>().To<MailController>();
// These are dependencies in MyApp.Domain that ARE NOT being bound properly by the current configuration, so I have to declare them manually
// They used to be injected automatically with version 2 of the conventions extention
kernel.Bind(typeof(IRepository<>)).To(typeof(Repository<>)).InRequestScope();
kernel.Bind<IUnitOfWork>().To<UnitOfWork>().InRequestScope();
kernel.Bind<IMemberServices>().To<MemberServices>();
kernel.Bind<IGrantApplicationServices>().To<GrantApplicationServices>();
// These are dependencies that SHOULD NOT be bound by convention as they require a different scope or have unique naming
kernel.Bind(typeof(EfDbContext)).ToSelf().InRequestScope();
kernel.Bind<IConfigurationProvider>().To<WebConfigConfigurationProvider>().InSingletonScope();
kernel.Bind<IAuthorizationProvider>().To<MyAppAuthorizationProvider>();
kernel.Bind<IPrincipal>().ToMethod(ctx => HttpContext.Current.User).InRequestScope();
kernel.Bind<IGrantApplicationDocumentServices>().To<MySpecialNameGrantAplicationDocumentServices>().InRequestScope();
}

The equivalent is:
kernel.Bind(x => x
.FromAssembliesMatching("*")
.SelectAllClasses()
.BindDefaultInterface());

Related

Set application version in SCDF from Java DSL

I'm trying to deploy a stream using Java DSL.
Here the code that creates stream (fluent style)
private void create() {
builder
.name(this.STREAM_NAME)
.source(source)
.sink(sink)
.create();
}
deployment method
private void deploy() {
dataFlowOperations.streamOperations().deploy(this.STREAM_NAME, new HashMap());
waitForStatus("deployed");
}
and a method that creates a bean for source application
#Bean
public StreamApplication source() {
return new StreamApplication("httpsource")
.addProperty("app.httpsource.version", "0.0.17")
.addProperty("spring.cloud.dataflow.httpsource.validation.schema", this.properties.getHttpSource().getJsonSchema());
}
I first trigger create method, then deploy. The problem is - I want to set application version to 0.0.17 for httpsource application, but final pod that is deployed for this app has image version equal to default version 0.0.1. Is it possible to set application version with Java DSL?
When deploying streams/tasks, optionally, you can pass in the version parameters as part of the deployment properties. Specifically, for versions, you'd pass them with the version.<APP_NAME> convention.
The DataflowIT presents such test combinations (see: sample); feel free to use it for reference. We rely on these tests for IT and as well as end-to-end Acceptance Tests.

No default instance or named instance 'Default' for requested plugin type

I'm trying to avoid referencing the concrete type library in my main project, but I'm getting this error:
No default instance or named instance 'Default' for requested plugin type StackExchangeChatInterfaces.IClient
1.) Container.GetInstance(StackExchangeChatInterfaces.IClient ,{username=; password=; defaultRoomUrl=; System.Action`2[System.Object,System.Object]=System.Action`2[System.Object,System.Object]})
I've setup my container to scan for assemblies, like so:
var container = new Container(x =>
{
x.Scan(scan =>
{
scan.AssembliesFromApplicationBaseDirectory();
scan.ExcludeNamespace("StructureMap");
scan.WithDefaultConventions();
scan.AddAllTypesOf<IMessageHandlers>();
});
//x.For<IClient>().Use<Client>(); //GetInstance will work if this line is not commented out.
});
When I try to get an instance, I get the error, my code for getting an instance is here:
chatInterface = container
.With("username").EqualTo(username)
.With("password").EqualTo(password)
.With("defaultRoomUrl").EqualTo(roomUrl)
.With<Action<object, object>>(delegate(object sender, object messageWrapper)
{
string message = ((dynamic)messageWrapper).Message;
Console.WriteLine("");
Console.WriteLine(message);
foreach (var item in messageHandlers)
{
item.MessageHandler.Invoke(message, chatInterface);
}
}).GetInstance<IClient>();
If I explicitly map the concrete class to the interface, everything works hunky dory, but that means I need to reference the project that Client is in, which I don't want to do.
This is really interesting. Looks like default conventions are not able to register types with such constructor (tried on both versions 2.6.3 and 3+). I was only registered when only parameterless constructor was specified. Looking at sources of both versions it is really suspicious as it should be registered. Deeper dive into the code would be needed...
Anyway try using custom registration convention:
public class ClientConvention : IRegistrationConvention
{
public void Process(Type type, Registry registry)
{
if (type.IsClass && !type.IsAbstract && !type.IsGenericType &&
type.GetInterfaces().Contains(typeof(IClient)))
{
registry.For(typeof(IClient)).Use(type);
}
}
}
Configure it like this:
var container = new Container(
c => c.Scan(
s =>
{
s.ExcludeNamespace("StructureMap");
s.WithDefaultConventions();
s.Convention<ClientConvention>();
s.AddAllTypesOf<IMessageHandlers>();
}));
and this should work just fine.
The default type scanning will not pick up concrete types whose constructor functions contain primitive arguments like strings, numbers, or dates. The thinking is that you'd effectively have to explicitly configure those inline dependencies anyway.
"but that means I need to reference the project that Client is in, which I don't want to do."
Does that actually matter? I think you're making things harder than they have to be by trying to eliminate the assembly reference.

Why should Ninject dlls be in the Web/bin folder? Can't I just put them in the GAC?

My company has got a deployment policy (I skip the details) such that any 3rd party software should be installed in the GAC, whilst our libraries are in Web/bin folder. But this approach doesn't work with Ninject and MVC 3/4. Let's follow an example:
This is my dependencies binding code:
public class RequestorDependenciesRegistration : NinjectModule
{
public override void Load()
{
Bind<IMyDearDependency>().To<MyDearImplementation>();
}
}
And this is my MVC controller:
public MyController(IMyDearDependency something) {
this.something = something; // 'something' is set only if Ninject dlls are in Web/bin... X-(
}
If Ninject dlls are in the GAC, it loads the module correctly, but when instantiating the MVC Controller the dependency is not injected (in some cases is null, in some cases MVC returns an error "No parameterless constructor etc etc"). If I manually copy Ninject*.dll in the Web/bin folder, than everything works fine, even without restarting IIS! Can't really understand why...
Even more surprisingly (for me), if I do something super-dirty like storing a reference to the Ninject Kernel instance in a public static property and use it as a ServiceLocator, it works! (Something dirty like this, in the MVC controller):
public MyController(IMyDearDependency something) { // 'something' is always null if Ninject is only in the GAC...
var controller = Kernel.Get<MyController>()
this.something = controller.something; // ... but this 'controller.something' is set, even if Ninject is only in the GAC!!! 8-O
}
Can anyone suggest me the reason why? And possibly a solution? :-) Many thanks!!
Ninject has a built in extension loading mechanism which is used to load the different extension like the Ninject.Web.Mvc.
But mechanism is looking only for the application folder to load the extensions so if your dll are in the GAC Ninject won't find them.
To solve this you can turn off the automatic extension loading and load the MvcModule module by hand when creating your StandardKernel:
var _kernel = new StandardKernel(
new NinjectSettings() { LoadExtensions = false },
new MvcModule(),
/* your other modules * /);

How can we support modular and testable patterns with ASP.NET MVC 4 and MEF 2?

We're trying to use MEF 2 with ASP.NET MVC 4 to support an extensible application. There are really 2 parts to this question (hope that's okay SO gods):
How do we use Microsoft.Composition and the MVC container code (MEF/MVC demo source) to replace Ninject as our DI for ICoreService, ICoreRepository, IUnitOfWork, and IDbContext?
It looks like we can't use both Ninject and the MVC container at the same time (I'm sure many are saying "duh"), so we'd like to go with MEF, if possible. I tried removing Ninject and setting [Export] attributes on each of the relevant implementations, spanning two assemblies in addition to the web project, but Save() failed to persist with no errors. I interpreted that as a singleton issue, but could not figure out how to sort it out (incl. [Shared]).
How do we load multiple assemblies dynamically at runtime?
I understand how to use CompositionContainer.AddAssemblies() to load specific DLLs, but for our application to be properly extensible, we require something more akin to how I (vaguely) understand catalogs in "full" MEF, which have been stripped out from the Microsoft.Composition package (I think?); to allow us to load all IPluggable (or whatever) assemblies, which will include their own UI, service, and repository layers and tie in to the Core service/repo too.
EDIT 1
A little more reading solved the first problem which was, indeed, a singleton issue. Attaching [Shared(Boundaries.HttpRequest)] to the CoreDbContext solved the persistence problem. When I tried simply [Shared], it expanded the 'singletonization' to the Application level (cross-request) and threw an exception saying that the edited object was already in the EF cache.
EDIT 2
I used the iterative assembly loading "meat" from Nick Blumhardt's answer below to update my Global.asax.cs code. The standard MEF 2 container from his code did not work in mine, probably because I'm using the MEF 2(?) MVC container. Summary: the code listed below now works as desired.
CoreDbContext.cs (Data.csproj)
[Export(typeof(IDbContext))]
[Shared(Boundaries.HttpRequest)]
public class CoreDbContext : IDbContext { ... }
CoreRepository.cs (Data.csproj)
[Export(typeof(IUnitOfWork))]
[Export(typeof(ICoreRepository))]
public class CoreRepository : ICoreRepository, IUnitOfWork
{
[ImportingConstructor]
public CoreRepository(IInsightDbContext context)
{
_context = context;
}
...
}
CoreService.cs (Services.csproj)
[Export(typeof(ICoreService))]
public class CoreService : ICoreService
{
[ImportingConstructor]
public CoreService(ICoreRepository repository, IUnitOfWork unitOfWork)
{
_repository = repository;
_unitOfWork = unitOfWork;
}
...
}
UserController.cs (Web.csproj)
public class UsersController : Controller
{
[ImportingConstructor]
public UsersController(ICoreService service)
{
_service = service;
}
...
}
Global.asax.cs (Web.csproj)
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
CompositionProvider.AddAssemblies(
typeof(ICoreRepository).Assembly,
typeof(ICoreService).Assembly,
);
// EDIT 2 --
// updated code to answer my 2nd question based on Nick Blumhardt's answer
foreach (var file in System.IO.Directory.GetFiles(Server.MapPath("Plugins"), "*.dll"))
{
try
{
var name = System.Reflection.AssemblyName.GetAssemblyName(file);
var assembly = System.Reflection.Assembly.Load(name);
CompositionProvider.AddAssembly(assembly);
}
catch
{
// You'll need to craft exception handling to
// your specific scenario.
}
}
}
}
If I understand you correctly, you're looking for code that will load all assemblies from a directory and load them into the container; here's a skeleton for doing that:
var config = new ContainerConfiguration();
foreach (var file in Directory.GetFiles(#".\Plugins", "*.dll"))
{
try
{
var name = AssemblyName.GetAssemblyName(file);
var assembly = Assembly.Load(name);
config.WithAssembly(assembly);
}
catch
{
// You'll need to craft exception handling to
// your specific scenario.
}
}
var container = config.CreateContainer();
// ...
Hammett discusses this scenario and shows a more complete version in F# here: http://hammett.castleproject.org/index.php/2011/12/a-decent-directorycatalog-implementation/
Note, this won't detect assemblies added to the directory after the application launches - Microsoft.Composition isn't intended for that kind of use, so if the set of plug-ins changes your best bet is to detect that with a directory watcher and prompt the user to restart the app. HTH!
MEF is not intended to be used as DI framework. Which means that you should separate your "plugins" (whatever they are) composition from your infrastructure dependencies, and implement the former via MEF and the latter via whatever DI framework you prefer.
I think there are a little misunderstandings on what MEF can and can't do.
Originally MEF was conceived as purely an extensibility architecture, but as the framework evolved up to its first release, it can be fully supported as a DI container also. MEF will handle dependency injection for you, and does so through it's ExportProvider architecture. It is also entirely possible to use other DI frameworks with MEF. So in reality there are a number of ways things could be achieved:
Build a NinjectExportProvider that you can plug into MEF, so when MEF is searching for available exports, it will be able to interrogate your Ninject container.
Use an implementation of the Common Services Locator pattern to bridge between MEF and Ninject or vice versa.
Because you are using MEF for the extensibility, you'll probably want to use the former, as this exposes your Ninject components to MEF, which in turn exposes them to your plugins.
The other thing to consider, which is a bit disappointing, is in reality there isn't a lot of room for automagically plugging in of features ala Wordpress on ASP.NET. ASP.NET is a compiled and managed environment, and because of that you either resort to late-binding by loading assemblies manually at runtime, or you restart the application to pick up the new plugins, which sort of defeats the object of being able to plug new extensions in through the application.
My advice, is plan your architecture to pick up any extensibility points as startup and assume that any core changes will require a deployment and application restart.
In terms of the direct questions asked:
The CompositionProvider accepts in instance of ContainerConfiguration which is used internally to create the CompositionContainer used by the provider. So you could use this as the point by which you customise how you want your container to be instantiated. The ContainerConfiguration supports a WithProvider method:
var configuration = new ContainerConfiguration().WithProvider(new NinjectExportDescriptorProvider(kernel));
CompositionProvider.SetConfiguration(configuration);
Where NinjectExportDescriptorProvider might be:
public class NinjectExportDescriptorProvider: ExportDescriptorProvider
{
private readonly IKernel _kernel;
public NinjectExportDescriptorProvider(IKernel kernel)
{
if (kernel == null) throw new ArgumentNullException("kernel");
_kernel = kernel;
}
public override IEnumerable<ExportDescriptorPromise> GetExportDescriptors(
CompositionContract contract, DependencyAccessor dependencyAccessor)
{
var type = contract.ContractType;
if (!_kernel.GetBindings(type).Any())
return NoExportDescriptors;
return new[] {
new ExportDescriptorPromise(
contract,
"Ninject Kernel",
true, // Hmmm... need to consider this, setting it to true will create it as a shared part, false as new instance each time,
NoDependencies,
_ => ExportDescriptor.Create((c, o) => _kernel.Get(type), NoMetadata)) };
}
}
}
Note: I have not tested this, this is all theory, and is based on the example AppSettingsExportDescriptorProvider at: http://mef.codeplex.com/wikipage?title=ProgrammingModelExtensions
It's different from using the standard ExportProvider, because using the CompostionProvider is built around lightweight composition. But essentially you're wrapping up access to your Ninject kernel and making it available to your CompositionContainer.
As with adding a specific new provider (see above), you can use the ContainerConfiguration to read the available assemblies, probably something like:
var configuration = new ContainerConfiguration().WithAssemblies(AppDomain.GetAssemblies())
Again, I haven't tested all of this, but I hope it at least points you in the right direction.

StructureMap: how to correctly set up default dependencies

An approach we've taken recently is to include a StructureMap registry in each of our assemblies that set's up the default dependencies.
We use a scanner to do this:
cfg.Scan(scanner =>
{
scanner.TheCallingAssembly();
scanner.Assembly("Assembly1");
scanner.Assembly("Assembly2");
scanner.Assembly("Assembly3");
scanner.LookForRegistries();
});
The idea is that we can then override the default dependencies from the main application.
The question is, where should we register these overrides? i.e. before we scan?, after we scan?
Furthermore, does the order of the assemblies specified in the scan expression, effect the order in which the dependencies are registered. So in the example above, would registries contained in the main application (TheCallingAssembly) get overrided by those in "Assembly3"?
Many thanks
Ben
Registries in TheCallingAssembly will be overridden by those you register in Assembly1, 2 etc.
So if you register ISomeInterface in everyone of those assemblies, the one in Assembly3 will be the default. The ones registered in the others assemblies you can get from structuremap by calling
container.GetAllInstances<ISomeInterface>();
This will return a IList of all the registered ISomeInterface in structuremap.
If you want to override the ones you get by scanning you have to configure the container again for some reason. If you don't do that, the last scanned type is the default.
In this example the ISomeInterface registered in Assembly1 is the default. When you look at the code, one would belive that SomeOtherClass is the default. But it is actually the one registered in Assembly1 that is the default.
var container = new Container(x => {
x.Scan(scanner =>
{
scanner.TheCallingAssembly();
scanner.Assembly("Assembly1");
scanner.LookForRegistries();
});
x.For<ISomeInterface>().Use<SomeOtherClass>();
});
So to override the mappings from the scanned assemblies. You have to configure the container again like this example. Here SomeOtherClass is the default for ISomeInterface.
var container = new Container(x => {
x.Scan(scanner =>
{
scanner.TheCallingAssembly();
scanner.Assembly("Assembly1");
scanner.LookForRegistries();
});
});
container.Configure(x => x.For<ISomeInterface>().Use<SomeOtherClass>());

Resources