質問

I am using .NET (MVC5, Web API etc). I understand constructor injection just about (fairly new to using it in anger). I have a class with a method that has a dependency. I don't want to use constructor injection because then I will be creating the dependent object every time this class is instantiated (and most of the methods don't use this dependent object). So I thought method injection sounded like it might be the thing. However I can't figure out how to do it (I am using Autofac).

So if my method is void DoSomething(string x, int y) and that method needs to use an implementation of IMyService, how do I do this without using the constructor injection?

The only method injection technique I have seen is one where effectively a method is called at instantiation. This doesn't seem to help my case, it still means that all instances create this dependency even if I am going to call a method that doesn't need it.

I'm sure it is something simple but I can't figure it out right now. Could you help me with an example please?

UPDATE

this is the crux of it. I like the idea of Lazy suggested by Jim and will try this. So is method injection as I suspected and if so I don't really understand the point of it - why use it instead of constructor injection?

public class MailService { 
   // lots of methods that don't need PlayerDataService 
   public void SendPlayersEmail() { 
       var service = new PlayerDataService(); 
       var players = service.GetPlayers(); 
       foreach(var player in players) { 
           SendEmail(player); 
       } 
   } 
}
役に立ちましたか?

解決 2

If the cost of instantiating your object during construction is an issue, you can wrap it in a Lazy<> to avoid unnecessary construction. This will cause your dependency to be constructed on the first call to the lazy's .Value.

他のヒント

I don't want to use constructor injection because then I will be creating the dependent object every time this class is instantiated (and most of the methods don't use this dependent object).

There's the problem. Break that functionality out into a new class.

That is, at least in my experience, the best solution when a method does not fit into the rest of the class (or have dependencies that are not used anywhere else).

You should also consider that object allocation is pretty cheap, you need millions of allocations per second before the performance is hurt (unless you are using Ninject ;))

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top