Search code examples
c#.netdependency-injectionasp.net-web-api2autofac

what the difference between RegisterInstance and RegisterType in DI Autofac


I am new in Autofac and i am trying to understand the difference between RegisterInstance and RegisterType in a web api 2 (.Net framework). Here in his doc have a simple example

var builder = new ContainerBuilder();


// Register individual components
builder.RegisterInstance(new TaskRepository())
       .As<ITaskRepository>();
builder.RegisterType<TaskController>();
builder.Register(c => new LogManager(DateTime.Now))
       .As<ILogger>();

// Scan an assembly for components
builder.RegisterAssemblyTypes(myAssembly)
       .Where(t => t.Name.EndsWith("Repository"))
       .AsImplementedInterfaces();

var container = builder.Build();

Can someone explain it?


Solution

  • RegisterInstance registers a single instance that will be then used as singleton.

    RegisterType leaves the creation and lifetime to the container. The default is usually per-request creation.