Search code examples
c#-4.0inversion-of-controlautofacmvc-mini-profiler

Bind an object to class in autofac and object can be null


I am using MiniProfiler in my project. To get an instance of the MiniProfiler, i have to use the following:

var profiler = MiniProfiler.Current;

This profiler object is what I want AutoFac to pass to every MiniProfiler Type when I create a class. Example I did the following:

    var profiler = MiniProfiler.Current;
    builder.RegisterInstance(profiler);

and in my controller I use the following way:

public ListingsController(IDataFetcher DataFetcher, ILog log, MiniProfiler profiler)
        {
            _DataFetcher = DataFetcher;
            _log = log;
            _profiler = profiler;
        }

The thing is the profiler instance can be null and I get the following server error when i run the code.

Value cannot be null.

See image: enter image description here

What needs to be done so that I can use Autofac with Miniprofiler? Or am I registering the object to the concreteType correctly?


Solution

  • Try registering a lambda so it's always the current instance instead of one specific instance.

    builder.Register(
      c => MiniProfiler.Current)
    .As<MiniProfiler>();