Autofac aop wildcard: is it possible? - autofac

The canonical way of using AOP in Autofac is to declare interceptor on each component:
builder.RegisterType<Filter1>().As<IFilter>()
.EnableInterfaceInterceptors();
In my project I have a lot (tens of) IFilter implementations, so adding and maintaining them is inconvenient. I would prefer an ability to intercept all instances of service. Something like:
builder.EnableInterfaceInterceptors<IFilter>();
Is it possible?

I am not sure if EnableInterfaceInterceptors can handle multiple registrations, but if it can this should work:
builder.RegisterAssemblyTypes(assemblies).Where(t => t.IsAssignableTo<IFilter>())
.EnableInterfaceInterceptors();
If you need, this can be wrapped into an extension method (like almost all the ContainerBuilder registration methods) to give you the exact syntax you requested above.

Related

is there any way to iterate two lists parallely in sightly?

Consider this code in java
for(int i=0,j=0;i<list1.size() && j<list2.size();i++,j++){
//do something
}
Can we do the similar thing in sightly? I tried best on my level but I couldn't find a way to do it. Please help on this.
There is no support for this kind of iteration and this is intended (in order to avoid putting your business logic in the HTL/Sightly template). You should instead invoke an Use-Api object which applies this logic and returns a collection of tuples from the two lists.
Adding to the answer posted by Vlad, You could either use
Sling Models
WCMUse class
server side javascript to perform such business logic
I would say it is better to use nodejs for such simple problems as it is more productive, easy to write and lives in the same folder as the sightly/HTL code.
For example, if your component name is 'componentA'
your HTL/sightly code is componentA.html residing inside componentA folder
and your business logic can be componentA.js residing in the same folder.
use(function() {
/*
Business logic
*/
return {
name: valueName,
list: listObject
};
});
Sling Models are very effective when you need to perform business logic using injected properties and resources. For example, a component that has several primitive and derived (from resource) properties.

How to resolve Autofac per-request service from custom attribute

I have configured my EF context configured like so
b.RegisterAssemblyTypes(webAssembly, coreAssembly)
.Where(t => t.IsAssignableTo<DbContext>())
.InstancePerLifetimeScope();
I would like to use it from a custom authorization attribute that hits the database using my EF context. This means no constructor-injection. I achieve this by using CommonSeviceLocator
var csl = new AutofacServiceLocator(container);
ServiceLocator.SetLocatorProvider(() => csl);
...
var user = await ServiceLocator.Current
.GetInstance<SiteContext>().FindAsync(id);
I am finding that this fails with a "multiple connections not supported" error if the browser issues two simultaneous requests to routes using this attribute. It seems like this might be due to what is mentioned in this answer. My guess is that ServiceLocator resolves from the root scope rather than the web request scope and the two request are conflicting (either request in isolation works fine).
This seems confirmed by that when I change to InstancePerRequest() I get this from any invocation of the attribute.
Autofac.Core.DependencyResolutionException No scope with a Tag matching 'AutofacWebRequest' is visible from the scope in which the instance was requested. This generally indicates that a component registered as per-HTTP request is
being requested by a SingleInstance() component (or a similar scenario.) Under the web integration always request dependencies from the DependencyResolver.Current or ILifetimeScopeProvider.RequestLifetime, never from the container itself.
So it seems like maybe ServiceLocator is simply not the way to go.
How do I resolve the request-scoped SiteContext from inside the attribute (using a service-locator pattern)?
Your issue derives from the fact that you are trying to put behavior inside of an Attribute. Attributes are for defining meta-data on code elements and assemblies, not for behavior.
Microsoft's marketing of Action Filter Attributes has led people implementing DI down the wrong path by putting both the Filter and the Attribute into the same class. As described in the post passive attributes, the solution is to break apart filter attributes into 2 classes:
An attribute that contains no behavior to mark code elements with meta-data.
A globally-registered filter that scans for the attribute and executes the desired behavior if present.
See the following for more examples:
Constructor Dependency Injection WebApi Attributes
Unity Inject dependencies into MVC filter class with parameters
Implementing passive attributes with dependencies that should be resolved by a DI container
Dependency Injection in Attributes: don’t do it!
Injecting dependencies into ASP.NET MVC 3 action filters. What's wrong with this approach?
How can I test for the presence of an Action Filter with constructor arguments?
Another option is to use IFilterProvider to resolve the filters as in IFilterProvider and separation of concerns.
Once you get your head around the fact that Attributes should not be doing anything themselves, using them with DI is rather straightforward.

How to mock multiple fields of same type in GwtMockito

I understand that #GwtMock annotation creates a mock of a particular type when run with GwtMockitoTestRunner, but what if I had multiple items of a particular type in my widget? For example if I had many buttons, or many anchors in my widget, is there a way to create mocks for each one individually?
Right now I am thinking of bypassing this shortcoming in my test with something like
#GwtMock mockButtonn;
and then later on
when(mockButton.something()).thenReturn(value1,value2,value3,...)
so I can distinguish the buttons based on order of invocation. But this is definitely unmaintainable. Can someone suggest an alternative?
There are a few different ways to use the mocks generated by GwtMockito, take a look at the documentation at http://google.github.io/gwtmockito/ if you haven't already. It depends on how you're creating your widgets:
If you're creating widgets via UiBinder (fields annotated with #UiField), you don't have to do anything special - they will automatically be filled with mocks when you call createAndBindUi. You can then reference them directly in your tests, e.g. when(myClass.myLabel.getText()).thenReturn("some text"). This works because fields have to be package-private for UiBinder, so you can see them from your tests.
If you're passing widgets into your class via its constructor or some other way (dependency injection), then just declare fields in your test using the normal Mockito #Mock annotation. GwtMockito will invoke Mockito to fill these in automatically, but otherwise it's just the same as any other Mockito mock.
If you're creating widgets via GWT.create, this is where #GwtMock is valuable. The only difference between #GwtMock and #Mock is that #GwtMock also makes it so any calls to GWT.create will return the object annotated with #GwtMock. So it doesn't really make sense to annotate multiple fields of the same type with #GwtMock, since GWT.create can return only one of them.
If you're creating widgets directly via new, don't do that! It will be impossible to create fake version for testing, and you should use dependency injection instead.
1 and 2 are the most common cases by far - it's somewhat uncommon to actually have to use #GwtMock.

Does GWT deferred binding return singletons of the same type within the scope of a single EntryPoint?

Let's say I have a number of GWT modules which are used as libraries, and one module with an entry point which inherits all of the library modules.
Each of the submodules needs to access a single instance of SomeClass.
If I call GWT.create(SomeClass.class) in modules A & B, do I get the same instance? If so, is this guaranteed?
No. GWT.create(SomeClass.class) compiles to new SomeClass(), unless there is a rebind rule of some kind - a replace-with or a generate-with rule will cause this to instead invoke the default constructor of whatever type is selected by those rules.
This means that GWT.create is not a suitable way to provide access to a singleton instance. Instead, consider some DI tool like Gin, or manual DI by always passing around the same instance. It is also possible to use the static keyword to keep a single instance where all code compiled into the same app can reference it.

How can I find out which bundle or plugin invoked (shared) code?

I want to create something like 'BundleLocal' variables, just like ThreadLocal variables, but instead of looking them up by Thread.currentThread() I need to look them up by bundle context.
The point is that I have a framework plugin 'F', and other plugins 'A', 'B', etc. using that framework. The framework contains a singleton which I want to refactor such that I have a singleton instance per bundle. MySingleton.getInstance() would then create/return a dedicated instance for each plugin. The problem is that within MySingleton.getInstance() I'd need to find out which of the plugins ('A', 'B', ..) called that method.
I could do it with a hack, obtaining the call stack with
StackTraceElement[] ste=new Throwable().getStackTrace();
and then querying the bundle context by class for each element:
org.osgi.framework.FrameworkUtil.getBundle(Class c).getBundleContext()
but sincerely hope that there exists a better way to obtain the bundle context or bundle id from within framework 'F'.
Any advice on how to do this more elegantly?
I would recommend to inject the information from where the call comes instead of trying to determine where it comes from. Something like this:
MyMultiton.getInstance(bundleContext)
Because of the modular nature of OSGi (and its isolated class loaders) singletons don't work (as you found out).
If you're refactoring, one option would be to simply add indirection. In ActivatorA:
public static Singleton getSingleton() {
Framework.getSingleton(BUNDLE_ID);
}
Then plugin A uses ActivatorA.getSingleton() and plugin B uses ActivatorB.getSingleton().
The other potential way is to provide a ComponentFactory and use Declarative Service to inject the appropriate Component (OSGi service) into plugin A and plugin B (everybody gets their own instance of the Component). But this is a more dynamic, more decoupled implementation of my first example.