Giter Club home page Giter Club logo

lightinject's People

Contributors

0xced avatar accidentaldeveloper avatar aidmsu avatar anatolfernandez avatar andmos avatar comkeendk avatar dadhi avatar danielkocean avatar danielmarbach avatar geirsagberg avatar haavamoa avatar illedan avatar kreediam avatar kvarv avatar mesakomarevich avatar modernist avatar oliverscode avatar pliner avatar rstm-sf avatar seesharper avatar shelakel avatar sirphilliptubell avatar timbussmann avatar tompazourek avatar tpluscode avatar vegar avatar vegardlarsen avatar

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  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  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

lightinject's Issues

IAssemblyLoader

Hi

I cant find any implementations of IAssemblyLoader. This means that RegisterAssembly("*.dll") always throws exceptions. Is there anything I am missing here?

Custom IHttpModule

Implement a custom IHttpModule that controls the scope per web request.

Problem with Html.RenderAction

I'm trying to use Html.RenderAction in my ASP NET MVC application with lightinject, but i received this error:

A single instance of controller 'WencoController' cannot be used to handle multiple requests. If a custom controller factory is in use, make sure that it creates a new instance of the controller for each request.

My global.asax has:
AreaRegistration.RegisterAllAreas();
var container = new ServiceContainer();
//register other services
container.Register<IProjectService, ProjectService>();
container.RegisterControllers();
container.EnableMvc();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);

How can i fix it? Do i need to configure something else?Plz help

Lazy<T>

Bring back support for Lazy and make sure it can be used as a decorator.

Problem with "Attempt to create a disposable instance without a current scope"

Hi
I'm using the get method of JQuery to return a json to fill a combobox, and also to receive an html and fill it in a div.
The problem is that It works in the first requests, but after that it throws an exception:
"Attempt to create a disposable instance without a current scope"
It looks related to lightinject.

How did it happen to me?And also, how can i fix it?
Thanks for your time

RegisterFallback

Composition roots must be executed before the fallback is invoked.

Possible performance improvement

Currently we create instance delegates like this:

Func<object>

This delegate calls into the delegate produced by the dynamic method.

Func<object[], object>

Look into calling the delegate directly instead of wrapping into another delegate.

Invalid operation exception on simple test

I am trying to run a simple test to see whether LightInject (NuGet package version 3.0.1.2) would be an appropriate solution for me, but I am getting an error on a basic test:

An unhandled exception of type 'System.InvalidOperationException' occurred in LightInject.dll

Additional information: Unable to resolve type: IoCContainer_Performance_Test.Program+Foobar, service name:

My code:

 public class Foobar
    {
        Dependency _dependency;
        public Foobar(Dependency dependecy)
        {
            _dependency = dependecy;
        }
    }

    public class Dependency
    {
        string test;

        public string Test
        {
            get { return test; }
            set { test = value; }
        }
    }

    static void LightInject()  
    {
        // 1. Create a new  container
        var container = new LightInject.ServiceContainer();

        // 2. Register type(s) to the container 
        container.Register<Foobar>(); 

        for (int i = 0; i < 10000; i++)
        {
            Foobar store =  container.GetInstance<Foobar>();//
        }
    }

Am I missing something in order to make it work properly?

Strongly typed dynamic method delegates

Current delegate looks like this

Func<object[], object>

Look into changing the delegate to

Func<object[], T>

This takes care of a lot of casting from and to object

Creating ChildContainers

I want to create a ChildContainer (a container that shares the parent's configuration, but can be configured with different settings or lifetime). My hunch is that we can use Scope to do this, but it's not clear to me how to do this.

Examples from other libraries related to what I'm looking to do:
Ninject: new ChildKernel(IKernel parentKernel)
Unity: parentContainer.CreateChildContainer()
Autofac: parentContainer.BeginLifetimeScope()
StructureMap: parentContainer.GetNestedContainer()

Binary distribution?

Hi,

This is an awesome package, but the source code-through-Nuget distribution doesn't work for me (I hate the fact that Nuget can even do that, a bit oldskool Java-ish me is).

For now I've simply compiled your library after changing all your classes to public, and put the dll on our internal Nuget stream.

I was wondering if this way of distributing LightInject is really necessary? Is there a technical reason for not distributing LightInject as a built .dll? Compiler optimizations, etc?

Perhaps providing both a binary package and a source package is acceptable?

Add the Configure method to allow execution of known composition roots.

Example

public class DataAccess : ICompositionRoot
{
    public void Compose(IServiceRegistry serviceRegistry)
    {
        serviceRegistry.Register(typeof(IConnectionFactory),typeof(ConnectionFactory));
        ---other services related to data access.
    }
}

By adding a new Configure method is is possible to configure all services related to data access in one simple step.

container.Configure<DataAccess>();

This means that all composition roots can be located in the production code and we can cherry-pick the "features" we need for each scenario such as an unit test without pulling in all available services in the container. This would potentially improve the start up time dramatically.

Internalize

Look into types that be marked as Internal

Move namespace to $rootnamespace$.LightInject

Put ServiceContainer.cs into a folder named LightInject. All extension projects should follow the same scheme so that the namespace matches the folder. This will also ensure that nothing has to change if a user decides to switch to the binary version.

Add ability to inject objects from the assembly based on custom predicate

After upgrading to a more recent version of LightInject (3.0.0.4) from ancient one (2.0.0.1) in search for a feature to register an external factory to create objects (Container.Register(x => MyORMContext.Instance.CreateUnitOfWork(), new PerRequestLifeTime());)
I've found out there are other problems with this version.

Previously in WPF project all Views and ViewModels registration was satisfied by running Container.RegisterAssembly(Assembly.GetExecutingAssembly());
For some reason this does not work anymore - I debugged previous version and it correctly extracts all types from assembly. I understand this might be excessive but it worked fine before.

Now there is a new alternative - registering by using factoryRule elements - does not work either on generic types (i.e. all objects inheriting from ViewModel and same with FrameworkElement).

So may I have 1 request and (possibly) 1 bug report:

Add calls allowing to register any type using a predicate:

Container.Register((t, s) => t.IsSubclassOf(typeof(ViewModel)));
Container.Register((t, s) => t.IsSubclassOf(typeof(FrameworkElement)), new PerRequestLifeTime());

And fix RegisterAssembly so it will find all types in the specified assembly (possibly limited to namespace)

I implemented new calls:

    /// <summary>
    /// Registers custom types otherwise unknown to the service container
    /// </summary>
    /// <param name="predicate">Determines if the service can be created by the <paramref name="factory"/> delegate.</param>
    public void Register(Func<Type, string, bool> predicate)
    {
        factoryRules.Add(new FactoryRule { CanCreateInstance = predicate, Factory = null });
    }
    /// <summary>
    /// Registers custom types otherwise unknown to the service container with a specified lifetime
    /// </summary>
    /// <param name="predicate">Determines if the service can be created by the <paramref name="factory"/> delegate.</param>
    public void Register(Func<Type, string, bool> predicate, ILifetime lifetime)
    {
        factoryRules.Add(new FactoryRule { CanCreateInstance = predicate, Factory = null, LifeTime = lifetime });
    }

(...)

var rule = factoryRules.Items.FirstOrDefault(r => r.CanCreateInstance(serviceType, serviceName));
if (rule != null)
{
if(rule.Factory == null)
{
Register(serviceType, serviceType, serviceName);
GetServiceEmitters(serviceType).TryGetValue(serviceName, out emitter);
}
else
{
emitter = CreateServiceEmitterBasedOnFactoryRule(rule, serviceType, serviceName);
}
}

(...)

In PerRequestLifeTime I needed to change something:

if (disposable != null)

to

if (disposable != null && scope != null)

as LI would complain otherwise, but this might be something related to 2 -> 3 migration.

I like LightInject for the "Light" part. Does the job pretty well and is flexible.

Is there an easier way to disable property injection than following ?

internal class AppPropertySelector: PropertySelector
{
    protected override bool IsInjectable(PropertyInfo propertyInfo)
    {
        return false;
    }
}

Sorry for too much information, at least it will all be in one place...

Thanks,

Mike

Mocking Collections

Hi
I have something like this:

public class Repository : IRepository
{
    private IDatabase db;
    public IEnumerable<IConnector> Connectors { get; set; }

    public Repository(IDatabase database, IEnumerable<IConnector> connectors)
    {
        db = database;
        Connectors = connectors;
    }
 .........
 ,,,,,,,,,

}

In my unit test I would like to do someting like:

   bla, bla
   container.StartMocking<IConnector>(() => connectorMock1.Object);
   container.StartMocking<IConnector>(() => connectorMock2.Object);
   bla,bla
  var repository = container.TryGetInstance<IRepository>();

Looking at repository.Connector it is always 1 element,, but I hoped for 2. Am I doing something wrong? Is it possible?

//regards
//lg

Why ServiceContract.cs class and not Dll

Hi,

Not exactly an issue, more a question to better understand the approach.

I haven't looked into the functionality, but just wondering why this is added as a file containing 51 class/interfaces and not as a referenced Dll?

Adding a file to the project means we now need to add a heap of exceptions both for testing the assemblies and code coverage to our build. As we have fairly strict coding rules we have also needed to include exceptions for that.

Regards
Allan

Leaking this

When a proxy returns "this", we must ensure that the proxy is returned.

This only needs to be implemented if the return type is the same as the target type.

Remember to implement this even for pass through methods.

Add support for Lazy<T> in decorators

Current we only support decorators with this constructor signature:

public class FooDecorator : IFoo
{
    public FooDecorator(IFoo foo) {}
}

Add support for lazy initialization of decoration target:

public class FooDecorator : IFoo
{
    public FooDecorator(Lazy<IFoo> lazyFoo) {}
}

NotImplementedException

The proxy type should throw a NotImplementedException for methods that is not handled by an interceptor.

Lazy Registration

For very large applications, it might not be a good solution to register all services up front. This can cause significant delay during startup and we need to provide some sort of lazy registration where services are registered when requested.

We need to hook into the process of resolving unknown services.

When an unknown service is requested, we will scan the assembly where the requested service type is contained. It will as usual look for composition roots and execute them if any are found in the assembly. Otherwise we will do a simple scan and register services using the standard conventions.

We also need to look into the mocking extensions as we might need to disable overwriting existing service registrations.

The next challenge is when the service type and the implementing type are contained in two different assemblies. The interface assembly will not have a reference to the implementing assembly. This could be solved by using an assembly attribute that is used to decorate the service assembly. This attribute gives LightInject a hint on the composition root type to be executed. This could be in the form of a Type or the type name.

public class CompositionRootAttribute : Attribute
{        
    public CompositionRootAttribute(Type compositionRootType)
    {

    }

    public CompositionRootAttribute(string typeName)
    {

    }

}

New Container on New Scoping

Hello.

I'm the author of the Liara Framework (http://prasannavl.github.io/Liara) which I recently started working on. I just came across LightInject, I thought it was perfect, and I'd like to use it as a default dependency resolver.

But everytime it returns a new scope, the same container object is used, which makes is extremely difficult in multi-threaded sitations, where a new thread could have a new scope.

By a quick glance at your code, I see the ScopeManager creating a new scope. Since, by the looks of it, all the services are ultimately stored into AvailableServices, would it be possible to create an overload to the container itself, that returns a new container with AvailableServices, and core objects directly assigned, and return a brand new container itself on a new scope?

Something similar to what TinyIoC does, which makes it perfect for muti-threaded scenarios, like Owin for instance.

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.