seesharper / lightinject Goto Github PK
View Code? Open in Web Editor NEWAn ultra lightweight IoC container
Home Page: http://www.lightinject.net
License: MIT License
An ultra lightweight IoC container
Home Page: http://www.lightinject.net
License: MIT License
Hi
I cant find any implementations of IAssemblyLoader. This means that RegisterAssembly("*.dll") always throws exceptions. Is there anything I am missing here?
void RegisterAssembly(string searchPattern, Func<Type, Type, bool> shouldRegister);
Implement a custom IHttpModule that controls the scope per web request.
Add a new EndMocking overload that ends all mocked instances.
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
Bring back support for Lazy and make sure it can be used as a decorator.
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
proxyDefiniton.AddCustomAttribute(() => new CustomAttribute());
Create a Expression visitor to figure out how the attribute was created.
The CompositeInterceptor should not create all interceptors upon initialization.
Composition roots must be executed before the fallback is invoked.
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.
I'm getting an InvalidOperationException - Attempt to end a scope before all child scopes are completed.
generated from:
https://github.com/seesharper/LightInject/blob/master/LightInject/LightInject.cs#L4948
So I'm pretty sure I've not got my scopes correct, but how do I find out what is wrong?
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?
Remember to set a dependency to LightInject >= 3.0.0.7
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
Write a test that
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()
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?
public ProxyDefinition AddCustomAttributes(CustomAttributeData[] customAttributeData)
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.
Look into types that be marked as Internal
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.
Remember to set dependency to LightInject >= 3.0.0.7
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
Change the behavior back to registering the concrete type as a service during assembly scanning.
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
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
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.
container.Intercept(m => m.IsDeclaredBy<SomeType>(), (invocationInfo) => invocationInfo.Proceed());
Even if multiple composition roots scans the same assembly, it should only be scanned once.
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) {}
}
The proxy type should throw a NotImplementedException for methods that is not handled by an interceptor.
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)
{
}
}
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.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.