Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return same instance for multiple interfaces

I'm registering components with the following code:

StandardKernel kernel = new StandardKernel();  string currentDirectory = Path.GetDirectoryName(GetType().Assembly.Location) foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) {     if (!Path.GetDirectoryName(assembly.Location).Equals(currentDirectory))          continue;      foreach (var type in assembly.GetTypes())     {         if (!type.IsComponent())              continue;          foreach (var @interface in type.GetInterfaces())         kernel.Bind(@interface).To(type).InSingletonScope();     } } 

Then I have a class which implements two interfaces:

class StandardConsole : IStartable, IConsumer<ConsoleCommand> 

If I resolve IStartable I get one instance, if I resolve IConsumer<ConsoleCommand> I get another.

How do I get the same instance for both interfaces?

like image 436
jgauffin Avatar asked Jul 07 '10 17:07

jgauffin


People also ask

Can a Type fulfill multiple interfaces?

A type can implement multiple interfaces.

Can interface inherit from class c#?

C# allows the user to inherit one interface into another interface. When a class implements the inherited interface then it must provide the implementation of all the members that are defined within the interface inheritance chain.

Why to use interfaces in c#?

Why And When To Use Interfaces? 1) To achieve security - hide certain details and only show the important details of an object (interface). 2) C# does not support "multiple inheritance" (a class can only inherit from one base class).

Can a Java file have multiple interfaces?

A Java class can implement multiple interfaces.


1 Answers

builder.RegisterType<StandardConsole>()    .As<IStartable>()    .As<IConsumer<ConsoleCommand>>()    .SingleInstance(); 

Very widely used feature of Autofac- any problems then there is a bug somewhere :)

Hth Nick

Edit By the looks of it, you're after the overload of As() that takes an IEnumerable<Type>() - check out all of the As() overloads using IntelliSense, something there should fit your scenario. As another commenter noted, you need to update the question with all of the info.

like image 181
Nicholas Blumhardt Avatar answered Sep 23 '22 19:09

Nicholas Blumhardt