Autofac how to pass configuration settings to base class - asp.net-mvc-4

Currently I am using Autofac as IoC.
I would like to pass configuration (appsettings) to my base class through I am calling rest services.
current structure is
class baseclass{
public baseclass(logger){}
}
class derivedclass : baseclass{
public derivedclass(IService service):base(logger)
{
}
}
there are more than 50 classed where i am refering baseclass so dont want to pass configuration for each one.
Can you please help to find solution.
Thanks

I assume that you don't want to change derived constructors to pass through your configuration. So you have some options:
Inject your configuration to your base class by property
Live without dependency injection (directly access to ConfigurationManager or some Service Locator pattern).
Although both options are bad practices and I recommend you to inject your configuration through constructors.

Related

Can I create a request-scoped object and access it from anywhere, and avoid passing it around as a parameter in JAX-RS?

Say I have a web service / a REST resource that is called with some HTTP header parameters. The resource method builds a complex data object (currently a POJO) and eventually returns it to the client (via Gson as JSON, but that doesn't matter).
So I have this call hierarchy:
#Path(foo) ProjectResource #GET getProject()
-> new Project()
-> new List<Participant> which contains lots of new Participant()s
-> new Affiliation()
If I want the Affiliation object to be e.g. populated in English or German depending on a header parameter, I have to pass that as a parameter down the chain. I want to avoid having to do that. Maybe this is just fundamentally impossible, but it feels so wrong. All these objects only live inside the request, so wouldn't it be convenient to be able to access information tied to the request from anywhere?
I was hoping I could e.g. define a CDI #RequestScoped object that initialized itself (or gets populated by some WebFilter) and that I can then inject where I might need it.
But obviously that doesn't work from inside the POJOs, and I also had trouble getting hold of the headers from inside the request-scoped object.
I've read many SO questions/answers about EJBs and JAX-RS Context and CDI but I can't wrap my head around it.
Am I expecting too much? Is passing down the parameter really the preferred option?
If I understand what you need, you can try the following (just wrote this solution from the top of my head, but it should work):
Defining a class to store the data you need
Define a class annotated with #RequestScoped which will store the data you need:
#RequestScoped
public class RequestMetadata {
private Locale language;
// Default constructor, getters and setters ommited
}
Ensure you are using the #RequestScoped annotation from the javax.enterprise.context package.
Creating a request filter
Create a ContainerRequestFilter to populate the RequestMetadata:
#Provider
#PreMatching
public class RequestMetadataFilter implements ContainerRequestFilter {
#Inject
private RequestMetadata requestMetadata;
#Override
public void filter(ContainerRequestContext requestContext) throws IOException {
requestMetadata.setLanguage(requestContext.getLanguage());
}
}
Performing the injection
And then you can finally perform the injection of the RequestMetadata using #Inject:
#Stateless
public class Foo {
#Inject
private RequestMetadata requestMetadata;
...
}
Please, be aware that anywhere is too broad: The injection will work into beans managed by the container, such as servlets, JAX-RS classes, EJB and CDI beans, for example.
You won't be able to perform injections into beans created by yourself neither into JPA entities.

Custom collection type is not being reused on WCF client Proxy side issue

I have defined the following type in a class library project.
[CollectionDataContract()]
public class OperationException:System.Collections.Generic.Dictionary<string,ExceptionData>
{
[DataMember()]
public bool ExceptionExists { get; set; }
}
[DataContract()]
public class ExceptionData {[DataMember()] public string Msg;}
On my WCF service end, I am returning an object which contains the above class as a child member variable like this.
[DataContract()]
public class SaveClient
{
[DataMember()]
public string Id;
[DataMember()]
public OperationException ExceptionCollection;
}
I have the OperationException class library referenced on the client side. The problem is when I generate the proxy using Add Service Reference, a new definition of OperationException of type dictionary is generated. I do have the Reuse Types option set to true. I like to have Actual 'OperationException' type being used since I have to pass this object to other methods.
Thanks in Advance..!
Iftikhar.
I had the same issue and like you I had applied the CollectionDataContract attribute and told the proxy generator to reuse types from my shared assembly.
The fix was not obvious, you need to supply a hook in the Reference.svcmap file on your client to tell the generator to use your custom collection type.
In Reference.svcmap edit the CollectionMappings element as follows and then update the service reference:
<CollectionMappings>
<CollectionMapping TypeName="YourSharedAssemblyNamespace.OperationException" Category="List" />
</CollectionMappings>
I think the same objective can be achieved if you are using svcutil from the command line by supplying the collection type argument.
/collectionType:YourSharedAssemblyNamespace.OperationException
See these posts for more info:
http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/09eefbbc-bf63-4aa3-a0cb-01a9dbd7f496/
http://www.codeproject.com/KB/WCF/WCFCollectionTypeSharing.aspx
I am not sure why the WCF proxy generator doesn't just use it's common sense to find the shared collection types but there you go, chalk it up as another funny from the WCF tool design.
Does your client proxy assembly have a project reference to the class library where the type is added?
If the proxies generated by svcutil are not what you want, it's also very easy to write them by hand. Just create your own ClientBase-derived class and implement your service interface on it. Then you have control over which assembly types you want to reuse.

Encapsulating WCF Proxies in Static Classes

I am designing a web service which will call different external web services according to the properties of a given object (a "request", for instance). A reference to these web services is added through the "Add Web Reference" menu in Visual Studio 2008, which, as you know, creates a proxy class for each endpoint which inherits from System.ServiceModel.ChannelBase<ISomeInterface> (where ISomeInterface is the endpoint defined by the specific service's WSDL).
The question is that I would like to encapsulate all those proxies in a single ServiceManager (for instance) static class containing, for example, an internal list of all the proxies, so that, on the one hand, all calls to a given service may go through ServiceManager instead of being scattered around the main application, and, on the other hand, new services which may be added latter can be made known to ServiceManager by a simple addition of a reference to the new proxy class.
I thought about desinging ServiceManager like
public static class ServiceManager
{
#region Properties
public static Dictionary<string, TProxy> ServiceList { get; private set; }
#endregion
}
but I don't know what I should replace TProxy by so that all of the different proxies can be called by using ServiceManager.ServiceList["ServiceName"]. Can anyone please help me out with this?
Since each service implements a different interface, it would have to be object... Unless you can create a common base interface, make the proxies inherit from that interface, and then create a List<MyBaseInterface>.
Why can't you just have one property on your class per proxy? At least then you could access the proxies in a strongly-typed way.
Do not reuse proxies. Re-instantiate them. Magic strings to differentiate between proxies are equally bad.
You are better off using static factories that return your service proxies than you are keeping only one instance of them.
Something like this:
public static class ServiceFactory
{
public static Proxy CreateProxy();
public static Proxy2 CreateProxy2();
// etc.
}

Remove dependancies on wcf services so I can unit test the class

I want to remove dependencies from my classes for WCF Services. I want to inject them into the constructor as an interface and then mock the interface when I am testing that class.
What is the best practice and the fastest way for doing this?
my class:
class Test
{
public IMyWCFInterface _wcf;
public Test(IMyWCFInterface wcf)
{
_wcf=wcf;
}
}
When you generate a WCF client proxy, an interface for the proxy should be generated for you. In addition, the generated client class that derives from ClientBase<TChannel> should implement that interface. Rather than depending on the class, depend on the interface, and inject an instance of the client class. That should resolve your problem.

How do I pass a service to another plugin?

I have a plugin that I will instantiate at runtime and I want to pass it a WCF service from the application host. The application host is responsible for creating the connection to the service. The reason for this is that a single service can be used by multiple plugins, but the plugins should only know about its interface since there may be several implementation of IMyPluginServices. For instance, the Run method of the plugin instance would be:
public void Run(IMyPluginServices services)
{
services.DoSomething();
}
The problem I am running into is that I don't know how to create a service of type IMyPluginServices and pass it to the Run function. The service reference generated by VS 2010 doesn't seem to create an object of type IMyPluginServices that I can pass to it. Any help would be greatly appreciated. Thanks.
When you add a service reference in VS 2010 for a service it generates an interface named IMyService which contains methods for each OperationContract in your service. It also generates a concrete class named MyServiceClient, which can be constructed and then used to invoke your service.
Now, the problem that you're running into, I believe, is that MyServiceClient is a subclass of ClientBase<IMyService>, and does not implement the generated IMyService interface (which is a real pain).
To get around this problem I ended up making a new interface:
public interface IMyServiceClient : IMyService, IDisposable, ICommunicationObject
{
}
(Note: IDisposable and ICommunicationObject are only required if you want your module to be able to detect/react to faulted channels and other such things).
I then extend MyServiceClient with a partial class (in the assembly that contains my WCF Service reference):
public partial class MyServiceClient : IMyServiceClient
{
}
Now in my modules I can accept an IMyServiceClient instead of an IMyService, and still execute all of the methods that I need to. The application in control of the modules can still create instances of MyServiceClient as it always did.
The beauty of this is that your new interface and partial class don't need any actual code - the definitions suffice to get the job done.