Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for async factory methods #23

Open
jpierson opened this issue Sep 3, 2014 · 1 comment
Open

Add support for async factory methods #23

jpierson opened this issue Sep 3, 2014 · 1 comment

Comments

@jpierson
Copy link

jpierson commented Sep 3, 2014

We use the Ninject factory extensions in a project that I'm working on and we have come across the need in some cases for async instantiation which has come into conflict with some of the auto-implemented factory goodness we have been enjoying.

The basic concept is to allow the factory extensions to work with methods (func or auto-implemented interface method contracts) that return a result of Task.

public class MyClass
{
   public MyClass(int nonServiceDependency, IMyService serviceDependency)
   {
      ...
   }
}

public class IMyClassFactory
{
   public async Task<MyClass> CreateMyClassAsync(int nonServiceDependency);
}

And usage would look something like.

kernel.Bind<IMyClassFactory>().ToFactory();

var factory = kernel.Get<IMyClassFactory>();
var instanceFromFactory = await factory.CreateMyClassAsync(42);

// or alternatively

var func = kernel.Get<Func<int, Task<MyClass>>>();
var instanceFromFunc = await func(42);
@remogloor
Copy link
Member

I think you should be able to extend that behavior quite easily by writing your own InstanceProvider

Pseudo Code:

class AsyncIP : StandardInstanceProvider()
{
    override Type GetType()
    {
        var baseType = base.GetType();
        if (baseType.IsTask) return baseType.GenericArgument[0];
        return baseType;
    }

    override object GetInstance()
    {
        if (ReturnTypeIsTask)
        {
            return GetMethodInfo(Task.Factory.StartNew<>).MakeGenericMethod(this.GetType())
                .Invoke(null, () => base.GetInstance());
        }
        return base.GetInstance();
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants