Resolve generics by type

125 Views Asked by At

I need to resolve some Quartz jobs from Autofac's LifeTimeScope. Currently I have implemented factory class:

public class JobWrapper<T> : IJob where T : IJob

In another class I have method that returns resolved job:

public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
    {
        Type type = bundle.JobDetail.JobType;
        return _lifetimeScope.Resolve<JobWrapper<type>>(); // does not work
    }

I need to pass generic to JobWrapper class and currently I don't know how to do that.

2

There are 2 best solutions below

10
On

You can describe the type yourself

// The type will be the Type for JobWrapper<CleanJob>
var type = typeof(JobWrapper<>).MakeGenericType(typeof(CleanJob));
return (IJob)container.Resolve(type);

// CleanJob decleration
public class CleanJob : IJob

There are some good examples for MakeGenericType here and here.

3
On

Well, I figured it out:

public class InjectorJobFactory : IJobFactory
{
    private readonly ILifetimeScope _lifetimeScope;

    public InjectorJobFactory(ILifetimeScope lifetimeScope)
    {
        _lifetimeScope = lifetimeScope;
    }

    public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
    {
        var type = typeof(JobWrapper<>).MakeGenericType(bundle.JobDetail.JobType);
        return (IJob)_lifetimeScope.Resolve(type);
    }

    public void ReturnJob(IJob job)
    {

    }
}

I just created another method and then just used MakeGenericMethod