Castle windsor logging facility - inversion-of-control

I'm trying to remove some logging dependencies and stumbled across Castle Windsor's logging facility. However, I'm kind of skeptical about whether I should use it or not.
public class MyClass
{
public Castle.Core.Logging.ILogger Logger { get; set; }
...
}
Windsor's logging facility requires that you expose your logger as a property. Is that really a good practice? I feel like I'm almost breaking encapsulation because normally when I reuse a component, I don't care about it's logging mechanism and I don't normally want to see it exposed.
If I use a custom wrapper that uses a static class to create the log, I can keep it private. For example:
public class MyClass
{
private static MyCustomWrapper.ILogger Logger = LogManager.GetLogger(typeof(MyClass));
...
}
I've searched the web for reasons why I should use the logging facility, but I'm only finding articles on how to use it, but not why I should use it. I feel like I'm missing the point. Having the logging component exposed is kind of scarying me away.

Windsor's logging facility requires that you expose your logger as a property.
Not necessarily. You can also put your logger as a constructor (i.e. mandatory) dependency. The logger is usually declared as a property (i.e optional dependency) because there might be no logger. That is, the component should be able to function without a logger.
If I use a custom wrapper that uses a static class to create the log
That's a service locator, that code couples MyClass to LogManager, which is IMHO worse than what you were trying to get away from.

Related

Dealing with state in factory implementations

What pattern would one use if you have multiple factory implementations, each of which requires different state information to create new objects?
Example:
IModelParameters: contains all the inputs and outputs to a complex calculation
IModelParameterFactory: has methods for getting and saving IModelParameter objects.
The issue is that one factory implementation might be getting your parameters from a database, with some state needed for retrieval, (i.e. a UserID), another might be getting your inputs from a file, in which case you don't have a UserID, but you do need a file name.
Is there another pattern that works better in this case? I've looked at some dependancy injection tools/libraries, and haven't seen anything that seems to address the situation.
Have you tried to put the requeriments in a class?
Every factory implementation has their own requeriments, but all requeriments classes derives form a base requeriment class (Or impements a requeriments interface). This allows you to have the same interface for all factory implementations, you just must do a cast to the correct requeriments class in every factory implementation.
Yes, casts are ugly and error-prone, but this method provides an uniform an extensible interface for your factory.
It's hard to say without seeing some code, but you may want to look into implementing a Repository Pattern. The Repository implementation would be responsible for retrieving the data that the factory then used to build its object(s). You could inject the repository interface into your factory:
public class ModelParameterFactory : IModelParameterFactory
{
private readonly IModelParameterRepository Repository;
public ModelParameterFactory(IModelParameterRepository repository)
{
Repository = repository;
}
...interface methods use the injected repository...
}
Then you would have, say a DatabaseModelParameterRepository and a FileModelParameterRepository. But I'm guessing you also have logic around which of those you would need to inject, so that calls for another factory:
public class ModelParameterRepositoryFactory : IModelParameterRepositoryFactory
{
public ModelParameterRepositoryFactory(...inputs needed to determine which repository to use...)
{
...assign...
}
...determine which repository is required and return it...
}
At this point, it might make more sense to inject IModelParameterRepositoryFactory into the ModelParameterFactory, rather than inject the IModelParameterRepository.
public class ModelParameterFactory : IModelParameterFactory
{
private readonly IModelParameterRepositoryFactory RepositoryFactory;
public ModelParameterFactory(IModelParameterRepositoryFactory repositoryFactory)
{
RepositoryFactory = repositoryFactory;
}
...interface methods get repository from the factory...
}
Whether you use a DI container or not, all logic regarding which repository to use and which factory to use are now moved into the relevant factory implementations, as opposed to the calling code or DI configuration.
While not terribly complex, this design nonetheless does give me pause to wonder whether your ModelParameterFactory and ModelParameters are too generic. You might benefit from teasing them into separate, more specific classes. The result would be a simpler and more expressive design. The above should work for you if that is not the case, however.
In my point of view, a state is something that you store in memory, such as static object, global variable, cache or session. Usually in DI, such states are not maintained, but being passed as a parameter. Example:
public IEnumerable<Records> GetRecordByUserId(string userId){ /*code*/ }
The userId is being passed instead being maintained in the repository.
However, when you want to make them as configuration-like instead of passing each time you do query, I think you can inject it as a wrapper class. See my question for more info. However, I don't recommend this design at repository, but I do recommend at service level.

JUnit test with GIN injection, without GWTTestCase and overloading gin modules?

I designed a new project using Guice/Gin so I could make our code more modular and swap-able especially when testing.
However, I am not able to find out how to make this work in practice. I was under the impression that I could just create a new Gin/Guice module in my test and install my 'base' module, overloading any bindings that I want to replace with specific testing implementations.
I don't want to have to use GWTTestCase and load my entire module, because it is very slow and unecissary for the types of granular testing I need to do.
I have tried using Jukito (http://code.google.com/p/jukito/), gwt-test-utils (http://code.google.com/p/gwt-test-utils/wiki/HowToUseWithGIN) and also some resources on doing this with guice (http://fabiostrozzi.eu/2011/03/27/junit-tests-easy-guice/).
None of these methods are yielding any results.
I think the Guice approach might work, if I defined a mirror guice module for my Gin module. However I really don't want to have to manage both of these. I really just want to test my GIN module like I would assume people test with Guice.
I feel like this should be really simple, can anyone point me to examples that work?
Update
Another way of looking at this question is:
How do I get the examples on the Jukito site (http://code.google.com/p/jukito/) work when the classes I am injecting are in an exernal Gin module?
**Update - In reference to Thomas Boyer's answer **
Thanks for the hint Tom, I was not able to find examples of using the adapter but I tried augmenting the Jukito examples to use the GinModuleAdapter anyway:
#RunWith(JukitoRunner.class)
public class MyGinTest {
public static class Module extends JukitoModule {
protected void configureTest() {
install(new GinModuleAdapter(new ClientModule()));
}
}
#Test
#Inject
public void testAdd(SyncedDOMModel mod){
assertNotNull(mod);
}
}
When I tried to run this test I recieved this exception:
java.lang.AssertionError: should never be actually called
at com.google.gwt.inject.rebind.adapter.GwtDotCreateProvider.get(GwtDotCreateProvider.java:43)
at com.google.inject.internal.InternalFactoryToProviderAdapter.get(InternalFactoryToProviderAdapter.java:40)
at com.google.inject.internal.ProviderToInternalFactoryAdapter$1.call(ProviderToInternalFactoryAdapter.java:46)
at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1031)
at com.google.inject.internal.ProviderToInternalFactoryAdapter.get(ProviderToInternalFactoryAdapter.java:40)
at com.google.inject.Scopes$1$1.get(Scopes.java:65)
at com.google.inject.internal.InternalFactoryToProviderAdapter.get(InternalFactoryToProviderAdapter.java:40)
at com.google.inject.internal.InternalInjectorCreator$1.call(InternalInjectorCreator.java:204)
at com.google.inject.internal.InternalInjectorCreator$1.call(InternalInjectorCreator.java:198)
at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1024)
at com.google.inject.internal.InternalInjectorCreator.loadEagerSingletons(InternalInjectorCreator.java:198)
at com.google.inject.internal.InternalInjectorCreator.injectDynamically(InternalInjectorCreator.java:179)
at com.google.inject.internal.InternalInjectorCreator.build(InternalInjectorCreator.java:109)
at com.google.inject.Guice.createInjector(Guice.java:95)
at com.google.inject.Guice.createInjector(Guice.java:72)
at com.google.inject.Guice.createInjector(Guice.java:62)
at org.jukito.JukitoRunner.ensureInjector(JukitoRunner.java:118)
at org.jukito.JukitoRunner.computeTestMethods(JukitoRunner.java:177)
at org.jukito.JukitoRunner.validateInstanceMethods(JukitoRunner.java:276)
at org.junit.runners.BlockJUnit4ClassRunner.collectInitializationErrors(BlockJUnit4ClassRunner.java:102)
at org.junit.runners.ParentRunner.validate(ParentRunner.java:344)
at org.junit.runners.ParentRunner.<init>(ParentRunner.java:74)
at org.junit.runners.BlockJUnit4ClassRunner.<init>(BlockJUnit4ClassRunner.java:55)
at org.jukito.JukitoRunner.<init>(JukitoRunner.java:72)
My gin module is part of a GWTP project, and looks like this:
public class ClientModule extends AbstractPresenterModule {
#Override
protected void configure() {
install(new DefaultModule(ClientPlaceManager.class));
bindPresenter(MainPagePresenter.class, MainPagePresenter.MyView.class,
MainPageView.class, MainPagePresenter.MyProxy.class);
bindConstant().annotatedWith(DefaultPlace.class).to(NameTokens.main);
bindPresenterWidget(MapTreePresenter.class,
MapTreePresenter.MyView.class, MapTreeView.class);
bindPresenterWidget(MapTreeItemPresenter.class,
MapTreeItemPresenter.MyView.class, MapTreeItemView.class);
bind(ResourcePool.class).to(DefferredResourcePool.class);
bind(WebSocket.class).to(WebSocketImpl.class);
}
}
As you can somewhat see, the class I am injecting in my test SyncedDOMModel, uses a WebSocket which I bind in my module. When I am testing, I don't want to use a real websocket and server. So I want to overload that binding in my test, with a class that basically emulates the whole thing. It's easier to just inject a different implementation of the WebSocket in this case rather than use mocking.
If it helps, this is a basic outline of the SyncedDOMMOdel class:
public class SyncedDOMMOdel {
....
#Inject
public SyncedDOMModel(WebSocket socket){
this.socket = socket;
}
....
}
You can use the GinModuleAdapter to use any GinModule as a Guice Module.
Obviously, you won't benefit from GIN's specific features: default to GWT.create() when something has no particular binding (this includes interfaces and abstract classes, which would throw in Guice), and automatically search for a RemoteService interface when an interface whose name ends Async has no specific binding.
And you won't be able to use anything that depends on JSNI or deferred binding (GWT.create()), as in any non-GWTTestCase unit test.

Avoiding the service locator with inversion of control while dynamically creating objects

I have a WPF application based on MVVM with Caliburn.Micro and Ninject. I have a root viewmodel called ShellViewModel. It has a couple of dependencies (injected via constructor) which are configured in Caliburn's Bootstrapper. So far so good.
Somewhere down the line, there is a MenuViewModel with a couple of buttons, that in turn open other viewmodels with their own dependencies. These viewmodels are not created during creation of the root object, but I still want to inject dependencies into them from my IoC container.
I've read this question on service locator vs dependency injection and I understand the points being made.
I'm under the impression however that my MenuViewModel needs to be able to access my IoC container in order the properly inject the viewmodels that are being made dynamically..which is something I'm trying to avoid. Is there another way?
Yes, I believe you can do something a bit better.
Consider that if there was no on-demand requirement then obviously you could make those viewmodels be dependencies of MenuViewModel and so on up the chain until you get to the root of the object graph (the ShellViewModel) and the container would wire everything up.
You can put a "firewall" in the object graph by substituting something that can construct the dependencies of MenuViewModel for the dependencies themselves. The container is the obvious choice for this job, and IMHO from a practical standpoint this is a good enough solution even if it's not as pure.
But you can also substitute a special-purpose factory instead of the container; this factory would take a dependency on the container and provide read-only properties for the real dependencies of MenuViewModel. Accessing the properties would result in having the container resolve the objects and returning them (accessor methods would also work instead of properties; what's more appropriate is another discussion entirely, so just use whatever you think is better).
It may look like that you haven't really changed the status quo, but the situation is not the same it would be if MenuViewModel took a direct dependency on the container. In that case you would have no idea what the real dependencies of MenuViewModel are by looking at its public interface, while now you would see that there's a dependency on something like
interface IMenuViewModelDependencyFactory
{
public RealDependencyA { get; }
public RealDependencyB { get; }
}
which is much more informative. And if you look at the public interface of the concrete MenuViewModelDependencyFactory things are also much better:
class MenuViewModelDependencyFactory : IMenuViewModelDependencyFactory
{
private Container container;
public MenuViewModelDependencyFactory(Container container) { ... }
public RealDependencyA { get { ... } }
public RealDependencyB { get { ... } }
}
There should be no confusion over what MenuViewModelDependencyFactory intends to do with the container here because it's so very highly specialized.

Serialize aspectj method in GWT

I've try to expose to the client(gwt) an aspectJ method through gwt-rpc, but the gwt client can't find the method defined in an aspect. The class that i expose implements IsSerializable and only it's method are visible to the client interface...the method added by their aspect contrariwise no. How i can fix this? thanks in advice.
p.s. i post a little example for more clarity:
this is the class...
public class Example implements IsSerializable{
private String name;
public setName(String name){
this.name=name
}
}
and this is the aspect...
privileged aspect Example_x{
public int Example.getVersion() {
return this.version;
}
}
The Example.getVersion() method is unavailable on the client side.
TNX
This won't work, as GWT needs access to the source of any Java class that is exposed to the client side. This is necessary to compile them from Java to Javascript. If you modify your classes using AspectJ, the added methods will not be visible to the GWT compiler and therefore not to the client.
I'd say AspectJ is simply the wrong tool for this task. If you want to add some methods to existing classes you could write a (possibly generic) container class that contains an instance of Example as well as the version information from Example_x.

How to use OSGi getServiceReference() right

I am new to OSGi and came across several examples about OSGi services.
For example:
import org.osgi.framework.*;
import org.osgi.service.log.*;
public class MyActivator implements BundleActivator {
public void start(BundleContext context) throws Exception {
ServiceReference logRef =
context.getServiceReference(LogService.class.getName());
}
}
My question is, why do you use
getServiceReference(LogService.class.getName())
instead of
getServiceReference("LogService")
If you use LogService.class.getName() you have to import the Interface. This also means that you have to import the package org.osgi.services.log in your MANIFEST.MF.
Isn't that completely counterproductive if you want to reduce dependencies to push loose coupling? As far as I know one advantage of services is that the service consumer doesn't have to know the service publisher. But if you have to import one specific Interface you clearly have to know who's providing it. By only using a string like "LogService" you would not have to know that the Interface is provided by org.osgi.services.log.LogService.
What am I missing here?
Looks like you've confused implementation and interface
Using the actual interface for the name (and importing the interface , which you'll end up doing anyway) reenforces the interface contract that services are designed around. You don't care about the implemenation of a LogService but you do care about the interface. Every LogService will need to implement the same interface, hence your use of the interface to get the service. For all you know the LogService is really a wrapper around SLF4J provided by some other bundle. All you see is the interface. That's the loose coupling you're looking for. You don't have to ship the interface with every implementation. Leave the interface it's own bundle and have multiple implementations of that interface.
Side note: ServiceTracker is usually easier to use, give it a try!
Added benefits: Using the interface get the class name avoids spelling mistakes, excessive string literals, and makes refactoring much easier.
After you've gotten the ServiceReference, your next couple lines will likely involve this:
Object logSvc = content.getService(logRef)
// What can you do with logSvc now?!? It's an object, mostly useless
// Cast to the interface ... YES! Now you need to import it!
LogSerivce logger = (LogService)logSvc;
logger.log(LogService.LOG_INFO, "Interfaces are a contract between implementation and consumer/user");
If you use the LogService, you're coupled to it anyway. If you write middleware you likely get the name parameterized through some XML file or via an API. And yes, "LogService" will fail terribly, you need to use the fully qualified name: "org.osgi.service.log.LogService". Main reason to use the LogService.class.getName() pattern is to get correct renaming when you refactor your code and minimize spelling errors. The next OSGi API will very likely have:
ServiceReference<S> getServiceReference(Class<S> type)
calls to increase type safety.
Anyway, I would never use these low level API unless you develop middleware. If you actually depend on a concrete class DS is infinitely simpler, and even more when you use it with the bnd annotations (http://enroute.osgi.org/doc/217-ds.html).
#Component
class Xyz implements SomeService {
LogService log;
#Reference
void setLog( LogService log) { this.log = log; }
public void foo() { ... someservice ... }
}
If you develop middleware you get the service classes usually without knowing the actual class, via a string or class object. The OSGi API based on strings is used in those cases because it allows us to be more lazy by not creating a class loader until the last moment in time. I think the biggest mistake we made in OSGi 12 years ago is not to include the DS concepts in the core ... :-(
You cannot use value "LogService"
as a class name to get ServiceReference, because you have to use fully qualified class name
"org.osgi.services.log.LogService".
If you import package this way:
org.osgi.services.log;resolution:=optional
and you use ServiceTracker to track services in BundleActivator.start() method I suggest to use "org.osgi.services.log.LogService" instead of LogService.class.getName() on ServiceTracker initializazion. In this case you'll not get NoClassDefFoundError/ClassNotFountException on bundle start.
As basszero mentioned you should consider to use ServiceTracker. It is fairly easy to use and also supports a much better programming pattern. You must never assume that a ServiceReference you got sometime in the past is still valid. The service the ServiceReference points to might have gone away. The ServiceTracker will automatically notify you when a service is registered or unregistered.