1

When setting a property via Dependency Injection (in this case a logging dependancy) is it "normal" to make the getter protected so that objects outside of the dependant object cannot call that property?

i.e.

public ILogger Logger { protected get; set; }

vs

public ILogger Logger { get; set; }

(I'm actually using null object pattern in these but that's beside the point).

I dont want to use constructor injection and yet via public property injection, it's not "right" for any other object to call this object's logger.

So above is what im going with but it does seem weird.

4

3 回答 3

1

Why do you need a getter for the logger at all?

Objects that you inject should be implementation details of the thing that they are injected into. So in general you should just have a setter for such items.

于 2012-10-12T04:23:26.113 回答
1

It doesn't matter that you have a public getter. Your implementation should implement an interface and consumers should depend on the interface, not the implementation. Because your Logger property is defined on the implementation, consumers will not have access to it. So there is no problem in having both a public getter and setter.

However, since you are already talking about the Null Object pattern, I assume that the logger is always injected. In that case, why not simply use constructor injection? Properties can be used for optional dependencies, but because of the use of the Null Object pattern, there is hardly ever a reason to define a property. If you find yourself defining a property because you want this logging dependency to be available for many types, please ask your self: Aren't I logging too much?

于 2012-10-12T08:30:42.487 回答
0

Generally, the getter methods are marked public (though there are purists who avoid getters also and expose well-defined actions on the object as methods) and setter methods are either avoided or marked protected/private only for the DI frameworks to be able to set the value on an object, after constructing the object using the no-arg default constructor. DI frameworks are capable of accessing protected/private methods using reflection, so the purpose to not expose setters would also be addressed.

于 2012-10-12T04:23:02.253 回答