Coder Social home page Coder Social logo

ninject.extensions.conventions's Introduction

Ninject

Build status codecov NuGet Version NuGet Downloads

Ninject is a lightning-fast, ultra-lightweight dependency injector for .NET applications. It helps you split your application into a collection of loosely-coupled, highly-cohesive pieces, and then glue them back together in a flexible manner. By using Ninject to support your software's architecture, your code will become easier to write, reuse, test, and modify.

Write your code so it's flexible...

public class Samurai {
    public IWeapon Weapon { get; private set; }
    public Samurai(IWeapon weapon) 
    {
        this.Weapon = weapon;
    }
}

...and let Ninject glue it together for you.

public class WarriorModule : NinjectModule
{
    public override void Load() 
    {
        this.Bind<IWeapon>().To<Sword>();
    }
}

Features:

  1. Focused. Too many existing dependency injection projects sacrifice usability for features that aren't often necessary. Each time a feature is added to Ninject, its benefit is weighed against the complexity it adds to everyday use. Our goal is to keep the barrier to entry - the baseline level of knowledge required to use Ninject - as low as possible. Ninject has many advanced features, but understanding them is not required to use the basic features.

  2. Sleek. Framework bloat is a major concern for some projects, and as such, all of Ninject's core functionality is in a single assembly with no dependencies outside the .NET base class library. This single assembly's footprint is approximately 85KB when compiled for release.

  3. Fast. Instead of relying on reflection for invocation, Ninject takes advantage of lightweight code generation in the CLR. This can result in a dramatic (8-50x) improvement in performance in many situations.

  4. Precise. Ninject helps developers get things right the first time around. Rather than relying on XML mapping files and string identifiers to wire up components, Ninject provides a robust domain-specific language. This means that Ninject takes advantage of the capabilities of the language (like type-safety) and the IDE (like IntelliSense and code completion).

  5. Agile. Ninject is designed around a component-based architecture, with customization and evolution in mind. Many facets of the system can be augmented or modified to fit the requirements of each project.

  6. Stealthy. Ninject will not invade your code. You can easily isolate the dependency on Ninject to a single assembly in your project.

  7. Powerful. Ninject includes many advanced features. For example, Ninject is the first dependency injector to support contextual binding, in which a different concrete implementation of a service may be injected depending on the context in which it is requested.

Everything else is in Extensions

Yes, sounds slim and focused, but where is the support for all the features that the competitors have?

Generally, they are maintained as specific focused extensions with owners who keep them in sync and pull in new ideas and fixes fast. These are summarized on the extensions section of the project website. Most are hosted alongside the core project right here.

License

Ninject is intended to be used in both open-source and commercial environments. To allow its use in as many situations as possible, Ninject is dual-licensed. You may choose to use Ninject under either the Apache License, Version 2.0, or the Microsoft Public License (Ms-PL). These licenses are essentially identical, but you are encouraged to evaluate both to determine which best fits your intended use.

Refer to LICENSE.txt for detailed information.

Changes history

Resources

ninject.extensions.conventions's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ninject.extensions.conventions's Issues

GetNameWithoutGenericPart Throws SubString exception

I'm liking the package but I ran into this issue.

On line 102 of file AbstractInterfaceBindingGenerator.cs, the string.SubString() method is called without first making sure that the IndexOf() call did not return -1. The following exception is thrown if the IndexOf() returns -1, which is not very useful when something went wrong with my Ninject bootstrapping.

"System.ArgumentOutOfRangeException: Length cannot be less than zero"

The call that I'm making which ultimately leads to this exception is the following.

kernel.Bind(x => x.FromAssembliesInPath(Directory.GetCurrentDirectory())
.SelectAllClasses().BindDefaultInterfaces());

Scan() code

All of the V2 releases have been removed, including the source modules. We are currently migrating from Ninject V2.2 ( including Conventions ) and the Scan() functionality is a key map/binding tool in our old code. We want to look at how Scan() worked. Is there a code archive of the V2.2 release available?

Get IAssemblyNameRetriever from Kernel instead of instanciating it

To speed up our Integration tests we currently replace the implementation of IAssemblyNameRetriever with one of our own which does not create a separate app domain.

To do so we currently need to roll our own implementation of the ExtensionsForIKernel.Bind method. This is due to the method doing new AssemblyNameRetriever();, so there is no way for us to override the implementation of IAssemblyNameRetriever.

We would like the extension to change to either
-get the IAssemblyNameRetriever from the Kernel
-let the Kernel build the entire IAssemblyFinder

Sadly there is currently no way to access the kernel's components or resolution features since there's only an IBindingRoot.

I've got some (rather ugly...) suggestions:

  • Extend IBindingRoot with functionality to acces resolution / components. Bad in regards to ISP.

or

  • The Convention extension could provide a module which resolves an instance of IAssemblyFinder or IAssemblyNameRetriever which is then stored in a static field - to be accessed by the extension method. Disadvantage: This does not work with multiple kernel instances. The last initialized kernel "wins".

Is there a way of registering decorators by conventions?

With SimpleInjector or StructureMap you have the possibility to register decorators by conventions.

Registration with SimpleInjector:
container.RegisterDecorator(typeof(ICommandHandler<>),typeof(ValidationCommandHandlerDecorator<>));

For now I did not find a way of registering decorators by convention in Ninject.
Is there a way of doing this?

using more then one WhereTypeInheritsFrom

maybe i don't understand it right but if i have a this code it works
kernel = new StandardKernel();
kernel.Scan(scanner =>
{
scanner.FromCallingAssembly();
scanner.WhereTypeIsNotInNamespace("NDjango");
scanner.FromAssembliesInPath(AppDomain.CurrentDomain.BaseDirectory);
scanner.WhereTypeInheritsFrom();
});

but if i have this code it does not work
kernel = new StandardKernel();
kernel.Scan(scanner =>
{
scanner.FromCallingAssembly();
scanner.WhereTypeIsNotInNamespace("NDjango");
scanner.FromAssembliesInPath(AppDomain.CurrentDomain.BaseDirectory);
scanner.WhereTypeInheritsFrom();
scanner.WhereTypeInheritsFrom();
});

it look like thee first WhereTypeInheritsFrom is excluding the other

Value cannot be null.\r\nParameter name: first

I'm trying to get Ninject set up with an ASP.NET MVC 4 project.

I have 3 projects in my solution. The main MVC 4 web app, that has references to 2 supporting assemblies (My.Services.dll and My.Repository.dll). My.Services.dll also has a reference to My.Repository.dll.

I have added the Nuget packages: Ninject.MVC3 (version 3.0.0.6) and Ninject.Extensions.Conventions (version 3.0.0.11)

In the main web application I have a Home controller with the following constructor

public HomeController(IMyService myService)
{
    _myService = myService;
} 

The service has a constructor like so:

public MyService(IMyRepository myRepository)
{
    _myRepository = myRepository;
}

In my NinjectWebCommon file I have:

private static void RegisterServices(IKernel kernel)
        {
            kernel.Bind(x =>
            {
                x.FromThisAssembly().SelectAllClasses().BindDefaultInterface();
                //x.FromAssemblyContaining<MyRepository>().SelectAllClasses().BindDefaultInterface();
                //x.FromAssemblyContaining<MyService>().SelectAllClasses().BindDefaultInterface();
                x.From("My.Repository", "My.Services").SelectAllTypes().BindDefaultInterface();

            });
        }         

If I run the application I get an error ("Value cannot be null.\r\nParameter name: first") on the last line of the RegisterServices method.

You can see in the code that I've also tried x.FromAssemblyContaining<MyRepository>().SelectAllClasses().BindDefaultInterface() to no avail.

Incidentally, If I put the 2 types, MyService and MyRepository in the web application and not in the satellite assemblies and remove the last line of RegisterServices then all dependecies are resolved and everything works correctly.

Anyone know what's wrong?

Bindings not loaded into Module

I have a problem that when using Conventions Extensions in a NinjectModule the Bindings are not added to the module.
Source files are attached
Perhaps the Problem is adding bindings to the kernel and not with the Bind method of the module.

gr33tz and thx

Modules.txt
Programm.txt

                                        `

WhereTypeInheritsFrom shouldn't have side effect

We just spent half a day tracking this issue down. The WhereTypeInheritsFrom registers a Binding Convention. It should not. I know that in issue #2 you seemed to indicate that this is desired behavior, however that really doesn't work. It is quite reasonable that I might want to select types by inheritance to bind with some other convention than WhereTypeInheritsFrom. I should be allowed to specify my own binding convention.

Furthermore, the regular expression you are using is incorrect. I believe you need to add ^ to the beginning and $ to the end. Currently WhereTypeInheritsFrom<IFoo>() would cause those types to be bound to interfaces such as IFooBar and UIFoo if they also implemented them.

The code where we had this problem is:
Kernel.Scan(x =>
{
x.FromAssemblyContaining();
x.WhereTypeInheritsFrom();
x.BindWithDefaultConventions();
x.InRequestScope();
});

In this case you can see we are using WhereTypeInheritsFrom with a type that isn't even an interface which is perfectly reasonable. But it causes the types to be bound to things like IUserRepoistory becuase they contain the word Repository in the type name.

2.4 documentation?

In the readme it says that 2.4 was a complete rebuild and that we should check the documentation. Where the heck is the documentation?

Binding types that have multiple generic interfaces of the same type

So say I have a type that implements interfaces like this:

public class MessageHandler : IHandle<MessageOne>, IHandle<MessageTwo>, IHandle<MessageThree> {
    ...
}

Binding with conventions doesn't seem to work when

IKernel container = new StandardKernel();
container.Bind(x =>
    x.FromAssemblyContaining<MessageHandler>()
        .SelectAllClasses()
        .InheritedFrom(typeof(IHandle<>))
        .BindToSelf())
);

var handlers = container.GetAll(typeof(IHandle<MessageOne>)); // handlers is just empty after trying to get the services

Is the open generic not supported??

A none backwards compatible change was made to minor version of the Ninject.Extensions.Conventions

Was as of 3.2

namespace Ninject.Extensions.Conventions.Syntax
{
///


/// The syntax to specify that none public types shall be included.
///

public interface IIncludingNonePublicTypesSyntax
{
/// Specifies that none public types shall be included.
/// The fluent syntax.
ISelectSyntax IncludingNonePublicTypes();
}
}

Is now as of 3.3

namespace Ninject.Extensions.Conventions.Syntax
{
///


/// The syntax to specify that none public types shall be included.
///

public interface IIncludingNonPublicTypesSyntax
{
/// Specifies that none public types shall be included.
/// The fluent syntax.
ISelectSyntax IncludingNonPublicTypes();
}
}

I understand the reason for the change, however it breaks https://semver.org/.

"public interface" with "internal class" implementation not supported

// ignore typos ;)

public interface IExample
{
    int Property { get; }
}

internal class Example : IExample
{
    public int Property
    { get { return 0; } }
}

public ExampleModule : NinjectModule
{
    public override void Load()
    {
        Bind( x => x
            .FromThisAssembly()
            .BindDefaultInterface() );
    }
}

This will not bind Example to IExample. Is this on purpose?

I expeted this to be working, since IExample could be used by anyone. The concrete implementation of the interface is not important to any users of the interface.

I really would like to have this setup working. (I would call this "injection in perfection" lolz)

BindBase does not bind abstract classes as expected

This issue stems from a StackOverflow question I posted yesterday.

I have a similar situation to this in my code, where I have a class that descends from two ancestor abstract classes, like so:

BaseAbstractClassExample <|-- AbstractClassExample <|-- ConcreteClassExample

When I do this binding:

kernel = new StandardKernel();
kernel.Bind(x => x.FromThisAssembly()
                    .SelectAllClasses().InheritedFrom<BaseAbstractClassExample>()                            
                    .BindBase());

I find that:

  • ConcreteClassExample is bound to itself
  • ConcreteClassExample is bound to AbstractClassExample
  • No bindings exist for BaseAbstractClassExample

Thanks to Daniel Marbach I understand why the BaseAbstractClassExample binding doesn't occur, but neither of us understand why the AbstractClassExample one exists. Is this expected behavior?

Named bindings by convention

I have a lot of implementations that would be good if all their bindings were named dynamically, pe. marking a class with a special attribute with the named instance. Currently, Named method only accepts string as a parameter, not a function like others that could use IContext. Is there a way to do what I'm trying to do currently with Ninject? Thank you.

this.Bind(
                ctx =>
                {
                    ctx.FromThisAssembly()
                       .SelectAllClasses()
                       .InheritedFrom<IReportGenerationManager>()
                       .WithAttribute<ReportPeriodicityAttribute>(attr => attr.Value == "Monthly")
                       .BindToSelf()
                       .Configure(
                            syntax => 
                                syntax
                                  .Named(/* I WANT HERE TO READ THE CLASS ATTRIBUTE TO NAME THE BINDING */)
                                  .WithConstructorArgument(
                                     "dataMartRepository",
                                      ctxArg => ctxArg.Kernel.Get<IDataMartRepository>("Monthly")));
                });

Bind Interfaces that are in Other Project / Assembly

Hi,
I am able to bind if the interface lies in the same project but if my Interfaces are in other Project then i am unable to bind them. I am using following code.

kernel.Bind(x =>
{
x.From("Leopard.Business")
.Select(type => type.Name.EndsWith("Business"))
.BindDefaultInterfaces();

            x.From("Leopard.Data")
                .Select(type => type.Name.EndsWith("Data"))
                .BindDefaultInterfaces();

        });

as long as my Interface are in same project this works but i want to move my interfaces in other project then it does not work. Plz help.

Ninject.Extensions.Conventions preventing update Service Reference

Hi,
I have a web application project with Ninject.Extensions.Conventions assembly referenced (VS 2012 / .NET 4.5).
When I try to update a Service Reference (WCF service) inside the project, it fails gracefully and remove the reference.cs file with the proxy class.
If I remove the Ninject.Extensions.Conventions reference and retry to update Service Reference, everything works fine.

Thanks

Where to find features like Scan

Hello,

I am referencing the Nuget-downloaded package and all I can seem to find are for functionality like Bind(this IKernel kernel) and so on. I see references in some of the blogs, SO, etc, that reference Scan, and so on, for functionality I might like to perform, but can't seem to find that functionality in the extensions I downloaded. Is there another branch, or a prior version(s) that might have implemented that?

Thank you...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.