Git Product home page Git Product logo

tinyioc's Introduction

Build status NuGet Version

Welcome to TinyIoC

Overview

Welcome to TinyIoC - an easy to use, hassle free, Inversion of Control Container. TinyIoC has been designed to fulfil a single key requirement - to lower the "level of entry" for using an IoC container; both for small projects, and developers who are new to IoC who might be "scared" of the "big boys"!

To that end, TinyIoC attempts to stick to the following core principals:

  • Simplified Inclusion - No assembly to reference, no binary to worry about, just a single cs file you can include in your project and you're good to go. It even works with both Mono and MonoTouch for iPhone development!
  • Simplified Setup - With auto-resolving of concrete types and an "auto registration" option for interfaces setup is a piece of cake. It can be reduced to 0 lines for concrete types, or 1 line if you have any interface dependencies!
  • Simple, "Fluent" API - Just because it's "Tiny", doesn't mean it has no features. A simple "fluent" API gives you access to the more advanced features, like specifying singleton/multi-instance, strong or weak references or forcing a particular constructor.

In addition to this, TinyIoC's "simplified inclusion" makes it useful for providing DI for internal library classes, or providing your library the ability to use DI without the consuming developer having to specify a container (although it's useful to provide the option to do so).

Note For ASP.Net per-request lifetime support you will need to also include TinyIoCAspNetExtensions.cs, and the TinyIoC namespace. This provides an extension method for supporting per-request registrations. It's an extra file, but it's preferable to taking a dependency on Asp.Net in the main file, which then requires users to setup #DEFINEs for non-asp.net platforms.

Key Features

  • Simple inclusion - just add the CS file (or VB file coming soon!) and off you go.
  • Wide platform support - actively tested on Windows, Mono, MonoTouch, PocketPC and Windows Phone 7. Also works just fine on MonoDroid.
  • Simple API for Register, Resolve, CanResolve and TryResolve.
  • Supports constructor injection and property injection. Constructors are selected automatically but can be overridden using a "fluent" API.
  • Lifetime management - including singletons, multi-instance and ASP.Net per-request singletons.
  • Automatic lazy factories - a Func dependency will automatically create a factory.
  • RegisterMultiple/ResolveAll/IEnumerable support - multiple implementations of an interface can be registered and resolved to an IEnumerable using ResolveAll, or taking a dependency on IEnumerable.
  • Child containers - lifetime can be managed using child containers, with automatic "bubbling" of resolving to parent containers where required.

tinyioc's People

Contributors

06b avatar alisonaquinas avatar coldacid avatar damianh avatar dreisenberger avatar dunksmith avatar evilbeaver avatar gillima avatar gkarabin avatar graemef avatar grayyang avatar grumpydev avatar jchannon avatar joaomsa avatar khellang avatar kppullin avatar marcosbozzani avatar mattminke avatar mbrit avatar nemo157 avatar niemyjski avatar olekria avatar phillip-haydon avatar richardhopton avatar rouacke avatar stepkie avatar thecodejunkie avatar xinmyname avatar xt0rted avatar yortw 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

tinyioc's Issues

How to unregister a type in TinyIoC?

I'm using TinyIoC and I want to unregister a type.

In the project wiki (https://github.com/grumpydev/TinyIoC/wiki), I could only find how to register types.

In the source code (https://github.com/grumpydev/TinyIoC/blob/master/src/TinyIoC/TinyIoC.cs), the closest thing of 'unregister' that I found was this method:

private void RemoveRegistration(TypeRegistration typeRegistration)
{
    _RegisteredTypes.Remove(typeRegistration);
}

But it is private and it isn't called anywhere.

Should this method be changed to public or is there a better way to do this?

How to change interface default lifetime?

I'm using NancyFx with TinyIoC and I would like to change the default behavior for interface dependency injection.

I would want it to be multi-instance instead of singleton.

I know I can register a specific interface/implementation to per request or singleton, but I cannot find a way to make this the default configuration for any interface dependency.

Thanks,
Rodrigo

ambiguous call between methods

I am trying to build a project with TinyIoC. (Win8, VS2012 sp3)

And get three errors:
Error 561 The call is ambiguous between the following methods or properties:
'TinyIoC.AssemblyExtensions.SafeGetTypes(System.Reflection.Assembly)' and 'TinyIoC.AssemblyExtensions.SafeGetTypes(System.Reflection.Assembly)'

Error 583 The call is ambiguous between the following methods or properties: 'TinyIoC.TypeExtensions.GetGenericMethod(System.Type, System.Reflection.BindingFlags, string, System.Type[], System.Type[])' and 'TinyIoC.TypeExtensions.GetGenericMethod(System.Type, System.Reflection.BindingFlags, string, System.Type[], System.Type[])'

Error 607 The call is ambiguous between the following methods or properties: 'TinyIoC.TypeExtensions.GetGenericMethod(System.Type, System.Reflection.BindingFlags, string, System.Type[], System.Type[])' and 'TinyIoC.TypeExtensions.GetGenericMethod(System.Type, System.Reflection.BindingFlags, string, System.Type[], System.Type[])'

Using the wrong string comparison

Attempting to compile this under Portable Library, I noticed that you are using the wrong string comparison - you're using InvariantCulture instead of Ordinal. Common mistake - hence why we removed it from Portable (and will be removed from .NET for Metro apps if it hasn't already been).

Think of InvariantCulture as en-US that basically doesn't change from .NET version to version, whereas ordinal is a byte-to-byte comparison. An example of two methods names that will be considered equal using invariant are 'encyclopaedia' and 'encyclopædia' despite the runtime considering them as different.

Feel free to ping offline if you would like more information.

David Kean
david DOT kean AT microsoft DOT com

Failing to inject property into ASPNET MVC controller

Hello everyone, I'm trying to simplify the injection code of my application using TinyIoC.
The application fails with the message: no parameterless constructor defined for this object. So it seems that TinyIoC is not injecting the constructor. I don't know if I'm missing something, but my code looks like the one in the docs.

The registrator

 public static class IocConfig
    {
        public static void Register()
        {
            var container = TinyIoCContainer.Current;

            container.Register<IPrincipal>(HttpContext.Current.User);

            container.Register<DatabaseContext>().AsPerRequestSingleton();
        }
    }

And a simple controller

public class HomeController : Controller
    {
        private DatabaseContext context;

        public HomeController(DatabaseContext context)
        {
            this.context = context;
        }

        public ActionResult Index()
        {
            return View();
        }
    }

Licence for TinyIoC

There is no Licence defined. This hinders the ability to use within commercial development as derived works cannot be licensed correctly.

Github provide a tool for setting a licence.

Issue with Object Creation (pcl + silverlight)

I'm running into the following issue: https://code.google.com/p/autofac/issues/detail?id=352 Seems to be a pretty common issue. Is there any chance we could fall back to a different implementation?

#define EXPRESSIONS                         // Platform supports System.Linq.Expressions
#define COMPILED_EXPRESSIONS                // Platform supports compiling expressions
//#define APPDOMAIN_GETASSEMBLIES             // Platform supports getting all assemblies from the AppDomain object
#define UNBOUND_GENERICS_GETCONSTRUCTORS    // Platform supports GetConstructors on unbound generic types
#define GETPARAMETERS_OPEN_GENERICS         // Platform supports GetParameters on open generics
#define RESOLVE_OPEN_GENERICS               // Platform supports resolving open generics
//#define READER_WRITER_LOCK_SLIM             // Platform supports ReaderWriterLockSlim
#define INTERNALIZE

And this is the stack trace.

TinyIoC.TinyIoCResolutionException occurred
  Message=Unable to resolve type: Exceptionless.Enrichments.Default.ConfigurationDefaultsEnrichment
  StackTrace:
       at TinyIoC.TinyIoCContainer.ConstructType(Type requestedType, Type implementationType, ConstructorInfo constructor, NamedParameterOverloads parameters, ResolveOptions options)
  InnerException: System.MethodAccessException
       Message=Attempt by method 'System.Linq.Expressions.Expression.CreateLambda(System.Type, System.Linq.Expressions.Expression, System.String, Boolean, System.Collections.ObjectModel.ReadOnlyCollection`1<System.Linq.Expressions.ParameterExpression>)' to access method 'System.Linq.Expressions.Expression`1<TinyIoC.TinyIoCContainer+ObjectConstructor>.Create(System.Linq.Expressions.Expression, System.String, Boolean, System.Collections.ObjectModel.ReadOnlyCollection`1<System.Linq.Expressions.ParameterExpression>)' failed.
       StackTrace:
            at System.RuntimeMethodHandle.PerformSecurityCheck(Object obj, RuntimeMethodHandleInternal method, RuntimeType parent, UInt32 invocationFlags)
            at System.RuntimeMethodHandle.PerformSecurityCheck(Object obj, IRuntimeMethodInfo method, RuntimeType parent, UInt32 invocationFlags)
            at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
            at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
            at System.Linq.Expressions.Expression.CreateLambda(Type delegateType, Expression body, String name, Boolean tailCall, ReadOnlyCollection`1 parameters)
            at System.Linq.Expressions.Expression.Lambda(Type delegateType, Expression body, String name, Boolean tailCall, IEnumerable`1 parameters)
            at System.Linq.Expressions.Expression.Lambda(Type delegateType, Expression body, ParameterExpression[] parameters)
            at TinyIoC.TinyIoCContainer.CreateObjectConstructionDelegateWithCache(ConstructorInfo constructor)
            at TinyIoC.TinyIoCContainer.ConstructType(Type requestedType, Type implementationType, ConstructorInfo constructor, NamedParameterOverloads parameters, ResolveOptions options)
       InnerException: 

pcl support

We have a pcl library and we last updated in 4/22/14 and since then a lot of the new changes have broke us when we use the following directives:

define EXPRESSIONS // Platform supports System.Linq.Expressions

define COMPILED_EXPRESSIONS // Platform supports compiling expressions

//#define APPDOMAIN_GETASSEMBLIES // Platform supports getting all assemblies from the AppDomain object

define UNBOUND_GENERICS_GETCONSTRUCTORS // Platform supports GetConstructors on unbound generic types

define GETPARAMETERS_OPEN_GENERICS // Platform supports GetParameters on open generics

define RESOLVE_OPEN_GENERICS // Platform supports resolving open generics

//#define READER_WRITER_LOCK_SLIM // Platform supports ReaderWriterLockSlim

define TINYIOC_INTERNAL

Is anyone else seeing these issues?

ASP.NET lifetime provider doesn't dispose

Unless I'm missing something, it looks like the ASP.NET lifetime provider does not dispose registered components at the end of a request. All registered components that are IDisposable should be disposed at the end of the request.

UsingConstructor() not working

I have a class with a constructor that takes 3 arguments:

  public CrmDbCommand(CrmDbConnection connection, IOrgCommandExecutor crmCommandExecutor, IOrganisationCommandProvider organisationCommandProvider)
        {

When an instance is resolved, I want TinyIoC to pass in null as the first argument into the constructor, but still resolve the other 2 arguments as normal.

So here is my registration:

            container.Register<CrmDbCommand>().UsingConstructor(() => new CrmDbCommand(null as CrmDbConnection, container.Resolve<IOrgCommandExecutor>(), container.Resolve<IOrganisationCommandProvider>()));

However when I do:

container.Resolve<CrmDbCommand>();

The outcome is that it doesn't invoke the constructor that I registered, so it does not pass in null as the first argument as desired.

Any advice / pointers much appreciated :)

ResolveAll() and ResolveAll<T>() do not return the same results

Hello,

If i have the following:

            var c = new TinyIoCContainer();
            c.Register<IXFormsApp>(App);
            var results3 = c.ResolveAll(typeof(IXFormsApp)).ToList();
            var results4 = c.ResolveAll<IXFormsApp>().ToList();

results3.Count <> results4.Count;

Shouldn't they be equal?

SafeDictionary has side effects

I just finished diagnosing an issue in my Monodroid app where my Activities were null after being registered with TinyIOC.

Turns out I registered them twice and on the second call:

_container.Register(this); //'this' is an Activity

in SafeDictionary....

public TValue this[TKey key]
{
set
{
lock (_Padlock)
{
TValue current;
if (_Dictionary.TryGetValue(key, out current))
{
var disposable = current as IDisposable;

                    if (disposable != null)
                        disposable.Dispose();
                }

                _Dictionary[key] = value;
            }
        }
    }

I really didn't expect calling register and passing 'this', would cause the object to be disposed. Easy enough to debug through, but counter-intuitive imho.

Would you consider a pull-request to make that configurable? Or to only dispose the object with the same key if it's a DIFFERENT object? I can't imagine any situatoin where a caller calling register and passing an instance would want that instance disposed.

Resolving open generics as singleton caches first request and returns for every other request

The title says it all.

NOTE: I am using ( and ) as angle brackets.

container.Register(typeof (IConfigurationProvider()), typeof (ConfigurationProvider()));

When I call Resolve, lets say, IConfigurationProvider(TestClass1), the result is as expected.

However, if I then call Resolve with IConfigurationProvider(TestClass2), I get a result of IConfigurationProvider(TestClass2).

I suspect it is because it is caching as singleton by default. I also suspect that changing the scope to multi-instance will resolve the issue. I need singleton instances for each requested generic type.

I suspect that the SingletonFactory should be storing a dictionary of types in case the singleton registration is an open generic.Regular types will store one item in the dictionary, where as open generic singletons will store an instance for each generic type.

More options on AutoRegister

I would be cool if .AutoRegister() had some options for lifetime similar to Register().AsMultiInstance() so that I could set the default for Interfaces to register as multi instance.

Add support for new coreclr

Have you considered support for running on the new coreclr?

I have hacked together a version which builds, but does not run. If this is something you are interested in and could help me fix I put together a pull request.

use $rootnamspace' instead of TinyIoc namespace

This will allow multiple libraries to use TinyIoc peacefully incase they are embedded.

The nuget file must be renamed from TinyIoc.cs to TinyIoc.cs.pp and namespace should be changed from namespace TinyIoc to namespace $rootnamespace$

Although I can change this manually without the once I download, it becomes a pain for me to update the file coz then nuget will tell the file was modified and will not update the TinyIoc.cs file.

Resolution does not handle default constructor parameters

Say I have a class that only has a constructor with an optional parameter like so:

public class Foo
{
    public Foo(int i = -1) { }
}

And I register it and try to resolve it:

container.Register<Foo>();
container.Resolve<Foo>();

Then TinyIoC will fail to resolve it because it doesn't think it has a value for the constructor parameter, but it could have used the default values.

It would require replacing the default parameters with explicit constructor overloads to work around this, but that may not always be possible (we may not have the code).

For info on how to reflectively invoke using the default parameter see: http://stackoverflow.com/questions/2421994/invoking-methods-with-optional-parameters-through-reflection

Registration required on child container for proper disposal

If services are registered on a parent container, calling Dispose on a child container will not call dispose on registered services. Services must be registered directly on each child container. This is not easy to do with a Web API dependency resolver, where you would create a child container on BeginScope. The only workaround I have found is to call AutoRegister on the child container, but this is not ideal.

It seems like calling Dispose on a child container should Dispose dependencies that were registered on the parent container if they were not also registered on the child container?

Resolving deeply (2+ levels) nested dependencies with dependencies in child container doesn't work as expected

I have something like:

internal class Service2 : IService2
{
    public IService3 Service3 { get; private set; }

    public Service2(IService3 service3)
    {
        this.Service3 = service3;
    }
}

internal class Service3 : IService3
{
}

internal class Service4 : IService4
{
    public IService2 Service2 { get; private set; }

    public Service4(IService2 service1)
    {
        Service2 = service1;
    }
}

internal class Service5 : IService5
{
    public Service5(IService4 service4)
    {
        Service4 = service4;
    }

    public IService4 Service4 { get; private set; }
}

I register Service2, Service4 and Service5 in my main container:

container.Register<IService2, Service2>().AsMultiInstance();

container.Register<IService4, Service4>().AsMultiInstance();

container.Register<IService5, Service5>().AsMultiInstance();

Then I add an instance of Service3 (the innermost dependency) to a child container:

var child = container.GetChildContainer();

var nestedService = new Service3();
child.Register<IService3>(nestedService);

And finally try to resolve IService5 (the outermost interface) from the child container:

var service5 = child.Resolve<IService5>();

I get an exception with the following:

TinyIoC.TinyIoCResolutionException: Unable to resolve type: IService5 ---> 
    TinyIoC.TinyIoCResolutionException: Unable to resolve type: Service5 ---> 
        TinyIoC.TinyIoCResolutionException: Unable to resolve type: Service5

Having stepped through this with the debugger, it seems to change context from the child container to the parent container when trying to resolve IService4, then it no longer has access to the concrete instance of IService3.

Select greediest non-obsolete constructor

I want TinyIoC to automatically select constructor, but I do not want TinyIoC to select a constructor marked with the ObsoleteAttribute.

Since this may break compability with current resolution behaviour, what about

Container.Register<MyClass>().IgnoreObsoleteConstructors();

or

Container.IgnoreObsoleteConstructors = true;

looking for contributor for jBeanBox project

Hi I thought this is a Java project but not, but still if you have interest of jBeanBox project can take a look, it's a small(only 1 java file ~1000 lines source code) but full function IOC/AOP tool.

ResolveAll doesn't check if implementations are in the container already

c.Register<T1>().AsSingleton();
c.RegisterMultiple(typeof(I1), new[] { typeof(T1) });
Assert.AreEqual(c.Resolve<T1>(), c.Resole<I1>().First())

the implementating types should be resolved from the container as well.

I'm basically doing this and it is failing

  • register several UIs as singletons
  • all UIs implement an interface - RegisterMultiple this interface to all UIs
  • resolve select UIs and show them
  • ....later
  • all UIs via the interface and dispose of them

Parameters passed to consturctor during resolving

It is possible to create new object with parameters passed to constructor.

For example:
TinyIoCContainer.Current.Resolve<ICar>("beRed")

I cannot use NamedParameters in some cases and should pass parameters in order how it is specified in constructor.

WinMo: Type.FindInterfaces missing

When using TinyIoC with Windows Mobile (PocketPC) the method off System.Type, FindInterfaces is missing.

Something like:

    public static Type[] FindInterfaces(this Type target, Func<Type, object, bool> filter, object filterCriteria) {
        if (filter == null) {
            throw new ArgumentNullException("filter");
        }

        var interfaces = target.GetInterfaces().Where(type => type != null);
        return interfaces.Where(@interface => filter(@interface, filterCriteria)).ToArray();
    }

Should do the trick.

Problem understanding ResolveAll<T> with ChildContainer Registrations

I am trying to understand how to use child containers with TinyIoCContainer.

I have a Parent Container, where I register the interface AnInterface with the implementation A. Then I open up a child container and register the interface AnInterface with the implementation B.

I would expect, that ResolveAll<AnInterface> on the child container returns either A and B (because I don't expect the child container to override the parent containers registrations), or only A or only B. I don't know what the actual expectation here is. But the actual result of ResolveAll returns the type B two times, which doesn't make much sense to me.

Or is it the expected outcome?

The Test case, that fails for me:

[Test]
public void ChildContainerResolveAll()
{
    using (var container = new TinyIoCContainer())
    {
        container.Register<AnInterface, A>();
        using (var childContainer = container.GetChildContainer())
        {
            childContainer.Register<AnInterface, B>();

            var registeredTypes = childContainer.ResolveAll<AnInterface>();

            Assert.AreEqual(2, registeredTypes.Count());

            Assert.IsTrue(registeredTypes.Any(x => x.GetType() == typeof(A)));
            Assert.IsTrue(registeredTypes.Any(x => x.GetType() == typeof(B)));
        }
    }
}

Auto register types from different namespace and different assmblies

I have a generic repository class in a different assembly and its generic implementation in different assembly, Container.AutoRegister does not identify and register it. Given the namespace is also different.

I need to register it explicitly:

container.Register(typeof(MyProject.Core.Repository.IRepository<>), typeof(MyProject.Data.Repository<>));

GetTypeConstructors method disregards non-public constructors.

Hey :) I was wondering if this is by design or not.
And if so what were the considerations that lead to such decision being made.

In a nutshell TinyIoC will fail to resolve a type if it does not find a public constructor, (which seems reasonable). ;)

Why resolve a type with a private constructor?
If it's private it's not meant to be instantiated by anyone, except the class owner, (we can all agree on that).

But what about when the constructor is internal.
Let's say you have an MVC controller, it doesn't make sense to make that type public, (you don't really want to expose it, you only consume the controller internally).
Heck, the MVC controller is just an example, any class that has an internal .ctor will fail to be resolved in TinyIoc. AFAIK.

This is were the "issue" lies.
https://github.com/grumpydev/TinyIoC/blob/master/src/TinyIoC/TinyIoC.cs#L3708

The quickest fix would be something like this:

const BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance;

return type.GetConstructors(flags)
    .Where(x => x.IsPrivate == false)
    .OrderByDescending(ctor => ctor.GetParameters().Length);

Similar fix here:
https://github.com/grumpydev/TinyIoC/blob/master/src/TinyIoC/TinyIoC.cs#L3254

Also, note that now we use the same binding flags everywhere concerning .ctor "location".
That makes it more predictable. ;)

t => (type.GetConstructors(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance)
    .Where(x => x.IsPrivate == false)
    .Count() == 0) &&
    !(t.IsInterface() || t.IsAbstract()),

Anyway those are my 5cents, I'll be more than happy to create a pull request to fix this, if such possibility arrises ;)

ResolveAll in constructor

Is this possible?

Something like this:

public MyClass(IConfiguration configuration, IEnumerable<IRouteFilter> routeFilters)

Where multiple IRouteFilter instances are registered and TinyIoCContainer.Current.ResolveAll<IRouteFilter>() works as expected

Does not compile under WinRT

I know this is a bleeding edge issue, but I wanted to use IoC in C# under WinRT, and your project came to mind as the perfect simple way for me to do this. I tried and failed because WinRT's reflection namespace does not seem to use BindingFlags in some of the GetMethod calls. It would be great if you could get this working, it might make you the first IoC that works under WinRT.

How to include in dnx console app project

I've got
"dependencies": {
"TinyIoC": "1.3.0",
...
in my project.json but after dnu restore, the dnu build fails with not finding the TinyIoC namespace. Eventually I just copied the file over, but I guess it's wrong. Is it?

TinyMessenger: Parameterize sender type in ITinyMessage and descendant classes

I'm working on a project where I'm finding myself repeatedly downcasting the Sender property in ITinyMessage and co to more concrete types to access their properties. So I thought it would be nice to have variants of ITinyMessage, TinyMessageBase, and GenericTinyMessage that take the sender type as a generic type parameter.

Here's an example of what it could look like using sender of type Foo, receiver of type Bar, and message of type FooHitTheBarMessage:

public class Foo
{
    public float Speed { get; private set; }

    //
    // Omitted details
    //
}

public class FooHitTheBarMessage : TinyMessageBase<Foo>
{
    public FooHitTheBarMessage(Foo sender)
        : base(sender)
    {   
    }
}

public class Bar
{
    public void Init()
    {
        MessageBus.Subscribe<FooHitTheBarMessage>(msg =>
        {
            TallyDamageBasedOnHitSpeed(msg.Sender.Speed);
        });
    }

    //
    // Omitted details
    //
}

Incorrect link in TinyIOC.cs

I thought you'd probably like to know that the link in Line 7 of TinyIOC.cs points toward your personal web site and not to GitHub.

AsPerRequestSingleton() looses parameters

Hi,
I have a type registration done like this:

ioc.Register().AsPerRequestSingleton();

Then I use it like this:

var parameters = new NamedParameterOverloads()
                                     {
                                         {"param1", this.TinyIoCContainer },
                                         {"param2", param2Object}
                                     };

This fails to resolve. I started to debug, and tracked the problem to CustomObjectLifetimeFactory.GetObject. The ctor parameters are passed to this method, but as this is the first time create such an object, it goes through if(current == null), and then it calls current = container.ConstructType, where it does not pass the parameters down the road. So it tries to construct TinyIoCContainer, and fails, as it looks like its not self-registered.

Anyway, even if TiNyIoCContainer were self-registered, this is wrong behavior, as it's not going to populate the parameter I'm passing.

This is the version from the latest NuGet.

I read the code in GitHub, and even if it has changed, still the call to container.ConstructType does not carry over the parameters, so most probably the problem is still there.

Does it look like a bug?

Cross domain component resolving

Does TinyIoC support cross domain resolving?
Let's say a parent's container in another AppDomain and contains remoting components that would be perfectly accessed in a current domain. Would they be resolved if a component in the current domain requires them?

BR,
Alexei

Nuget as DLL not CS

When installed via NuGet it adds a CS file to your project(s). If you have multiple projects, and they reference each other, you can't put TinyIoC into both projects, as the build will fail with ambiguous call errors. It also may prevent builds due to stylecop or fxcop errors.

There is no licensing information for TinyIoC in GitHub

Since the move to GitHub the licensing information is no longer associated with the project.

The old Bitbucket site has a license listed as Ms-PL however this information is no longer part of the GitHub project.

Could you include at least a license.txt file in the root of the project, and also if possible update the readme to reference it.

Wiki typo

https://github.com/grumpydev/TinyIoC/wiki/Registration---lifetimes

The text explicitly says RegisterMultiple, but the code uses Register (which doesn't compile).

container.Register<IMyMarkerInterface>(new[] { typeof(MyImplementationClass1), typeof(MyImplementationClass2) });

// should be

container.RegisterMultiple<IMyMarkerInterface>(new[] { typeof(MyImplementationClass1), typeof(MyImplementationClass2) });

Balancing Auto-Resolving Named Instances for Scheduling

Pardon if i have missed a previous example, but I was wondering if there is a way to define in the registration a method by which the auto-resolve for constructor injection (NancyFx) could resolve between several named instances the best one to use given an expression or even just use round robin to determine the next instance to return.

This would help me manage several classes that are used for scheduling long running processes for which I need to constrain the number of instances.

It looks like NamedParameterOverloads maybe an option, but was hoping that this could be done automagically with constructor injection.

Thanks in advance!

Uri ctor parameters causes a StackOverflowException

The following sample will result in a StackOverflowException

class Program
{
    static void Main(string[] args)
    {
        var container = TinyIoC.TinyIoCContainer.Current;

        var x = container.Resolve<Foo>();
    }
}

public class Foo
{
    public Foo(Bar b)
    {
    }
}

public class Bar
{
    public Bar(Uri u) // The Uri parameter causes a StackOverflowException
    {

    }
}

Registering Open Generic Types Fails

Attempting to Register:

Register(typeof(IThing<>), typeof(DefaultThing<>)).AsSingleton();

fails with:
TinyIocRegistrationException : Type DefaultThing1 is not valid for a registration of type IThing1
----> System.ArgumentException : Invalid generic arguments
Parameter name: typeArguments

Change Registration at run time?

Hi,

I have two concrete implementations for an interface. One is these is always used except for when a Demo mode is enabled. How can I change the implementation at run time when this happens? I don't see a Remove or Replace function on the container.

Thanks

There is no way of inspecting the registered types programatically

In a Bootstrapper class in my project I have a simple mechanism that automatically registers all interfaces found in the assemblies of the current AppDomain with concrete implementations of that interface found found in the assemblies of the current appdomain into a TinyIoC container.

Be default this autoregistration should not override/change existing registrations that already have been done prior to the AutoRegister call. Unfortunately this doesn't seem to be possible because there is no way of looking at the current registrations of the TinyIoC container (_RegisterdTypes is private).

Is there a way to inspect the current registrations? If not why not and can this feature be added? It would be very easy to implement (just a public facade around _RegisteredTypes).

Of course I could just add this myself in my local copy of TinyIoC.cs but that would break with the next update.

iOS Device - Compiled Expressions

iOS device does not support compiled expressions. The expressions will work fine on the iOS simulator, but as soon as you deploy to a device, it will fail.

I think there should be a quick note on your wiki documentation about using TinyIoC with Xamarin iOS (formerly MonoTouch) as your work is becoming the recommendation recommended to use on that platform.

I would also update the #if PocketPC || WINDOWS_PHONE to include something like IOS_DEVICE so that it might be apparent from code as well.

Took me a while to figure this out and just want others to be able to resolve this quicker than I in the future.

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.