I have an asp.net mvc application and need to call wcf service in it. I've added service reference to the project. I use unity for dependency injection and want to inject wcf client. But it's not so simple because of System.ServiceModel.ClientBase. I did it this way.
This is an autogenerated proxy:
public partial class WcfServiceClient :
System.ServiceModel.ClientBase<WcfUnity.IWcfServiceClient>,
WcfUnity.IWcfServiceClient
{
//autogenerated constructors and methods
}
I created interface:
public interface ISimpleProxy : WcfUnity.IWcfServiceClient
{
//duplication of methods' signatures
void CloseConnection();
}
I extended WcfServiceClient using partial class:
public partial class WcfServiceClient : ISimpleProxy
{
public void CloseConnection()
{
try
{
Close();
}
catch (Exception)
{
Abort();
}
}
}
And inject it like this:
container.RegisterType<ISimpleProxy>(new InjectionFactory(c => new WcfServiceClient()));
So I don't have dependecies from ClientBase and there is no wcf stuff inside classes which use this wcf proxy. Does this solution have some disadvatages?
No, it doesn't, I use (mostly) the same approach.
I would recommend you making your interface inherit from IDisposable, because underlying ClientBase<T> is disposable. This way you won't need CloseConnection.
Related
I have created one Parent library where in, I have a abstract class,and I have another child library where I have inherited the parent library, now I'm consuming this child library in web API controller, so, I would be consuming this in service layer,however, I'm not sure how to use it correctly, secondly I have all, the methods inside this library as protected, please guide how to do dependency injection for abstract class or do I need to create another interface or something for DI?
Code:
// Parent library
public abstract class Page
{
protected abstract void ImplementAbstractMethod();
}
// Child library
public class ImplementPage : Page
{
protected override void ImplementAbstractMethod()
{
// Implementation...
}
}
// Web API
public class ServiceController
{
public ServiceController( ????) // How to do dependency injection, should I use abstract class, if yes then how to consume protected method, or, do I need to make it public?
{
}
}
// Or In business layer
public class Service
{
public Service( ????) // How to do dependency injection, should I use abstract class, if yes then how to consume protected method, or, should I inherit the child library??
{
}
}
Its easy enough using NInject to establish dependency injection using interfaces.
So for example say I have a class like
public class WindowManagerService : IWindowManager
{
public WindowManagerService(ILogger logger) { }
}
It's easy to do something like this:
public class NinjectModuleLoader : NinjectModule
{
public override void Load()
{
this.Bind<IWindowManager>().To<WindowManagerService>().InSingletonScope();
}
}
and successfully configure the dependency injection.
However the problem I run into is when I need to provide a concrete instance of a class into the constructor such as the following example:
public class ObservableLogger : ILogger
{
public ObservableLogger(Dispatcher dispatcher) { }
}
In the above example I require the ability to pass in a concrete implementation of the dispatcher as I cannot use DI to establish this link and must reference the application wide Dispatcher instance.
Essentially what I wish to be able to do is something like this:
this.Bind<ILogger>().To(new ObservableLogger(Dispatcher)).InSingletonScope();
So how does one provide concrete implementations of dependencies to the NInject dependency manager?
You could use a factory method:
this.Bind<ILogger>().ToMethod(context => new ObservableLogger(Dispatcher));
...or create your own custom provider as explained in the docs: https://github.com/ninject/Ninject/wiki/Providers,-Factory-Methods-and-the-Activation-Context
There is also the ToConstant and ToConstructor methods:
this.Bind<ILogger>().ToConstant(new ObservableLogger(Dispatcher));
Please refer to this blog post for more information.
I have the following class:
public class ExampleClass
{
private readonly Service service;
public ExampleClass()
{
service = new Service();
}
private void ExecuteProcess()
{
var request = Transfer.RequestParameters;
service.SyncMethod(request);
}
}
I'm trying to fake the private readonly Service service, that is created in the constructor, because I want to ignore the call to service.SyncMethod(request).
Does anyone know how I can do this?
you can use Typemock's Isolator for faking the Service instance and for invoking the private method,for example:
[TestMethod]
public void TestMethod1()
{
Service faked = Isolate.Fake.NextInstance<Service>(Members.ReturnRecursiveFakes, ConstructorWillBe.Called);
ExampleClass exClass = new ExampleClass();
Isolate.WhenCalled(() => faked.SyncMethod(null)).IgnoreCall();
Isolate.Invoke.Method(exClass, "ExecuteProcess");
}
Provide a parameterized constructor as follows:
public ExampleClass(Service obj)
{
service = obj;
}
Then you could mock and pass the service object to the above constructor & test the function.
It is also recommended to code against an interface, in your case, create an IService, implement it in Service. Then you could inject the interface into the ExampleClass instead of the concrete implementation.
I think you should use something called 'Dependency injection'. This can be done quite easily with for example Ninject or Unity.
The result is that you do not create the service in ExampleClass, but instead pass an object of type IService to the constructor.
The interface has a method SyncMethod.
You let Service implement interface IService. You create a TestService or something that also implements IService.
In your TestService object you can make an empty implementation of the method SyncMethod to ignore it.
Your class in its current state is too tightly coupled to the dependent service, making it difficult (but not impossible) to mock dependencies to be able to test the class in isolation.
First classes should depend on abstractions and not on concretions. So abstract the Service behind an interface to allow for it to be more flexible when maintaining and testing your code in isolation.
For example
public interface IService {
void SyncMethod(RequestParameters request);
}
public class Service : IService {
//..code removed for brevity
}
Then refactor your class to follow the Explicit Dependencies Principle. This approach is known as "constructor injection".
public class ExampleClass {
private readonly IService service;
public ExampleClass(IService servic) {
this.service = service;
}
private void ExecuteProcess() {
var request = Transfer.RequestParameters;
service.SyncMethod(request);
}
}
In production, the actual dependency will be registered with the dependency container in the composition root and when the class is being resolved, the dependencies will be realized and injected into the dependent class.
This also allows for mocks/fakes/stubs to be used during testing either manually or with a mocking framework/tool of your choice.
I having a bit of trouble getting my head around Ioc and generics, and particularly how my company has set up the layers in relation to this. We're working under an MVP architecture.
I have a Car class:
class Car : ICar
{
IList<IWheel> wheels{get;set;}
IEngine engine{get;set;}
string registrationplate {get;set;}
public Car(){}
}
and I want to be able to get a newly created ICar, and I also want to be able to find an ICar by Id. Problem is I'm not sure why some of the design choices have been made in the project I'm working on. The structure for other services already created is as follows:
I have a Car and WHeel Service :
class WheelService : BaseService
{
IWheel wheel;
public IWheel Create()
{
return new wheel()
}
}
class CarService : BaseService
{
WheelService wheelservice;
public ICar CarCreate()
{
wheelservice = new Wheelservice()
car = new Car();
IWheel wheel = wheelservice.Create();
car.wheels.add(wheel);
return car;
}
public ICar Find(int id)
{
return (Car)base.Find<Car>(id);
}
}
Firstly, I'm finding the 'have a service for each entity' odd. I wouldn't have thought that a weak entity would have a service. My thoughts would be that the CarService create method would act like a factory method, without having to call a wheel service.
Also, the wheel service create method is actually used in the presenter code to return an IWheel all the way down to the UI, so that values can be set and passed back up. Again this, seems odd to me. Means the presenter can request the full ICar object from the UI.
Is the dependency in the Service create method normal? I would have thought that this would be brought in through IoC. But, if the ICar Create method was to handle all creation (including wheel, etc), then presumably the container would contain lots of interfaces in relation to this particular service?
If I were to bring in the interfaces, I would need to adjust the CarService.Find method, which is currently using concrete classes. It uses the BaseService, and it is solely this layer which interacts with the container to get the correct repository:
class BaseService
{
private object myRepository;
protected T GetRepository<T>(Type serviceType)
{
if (myRepository == null)
{
myRepository = (T)IoCRepositoryFactory.GetRepositoryInstance(typeof(T), serviceType);
}
return (T)myRepository;
}
protected virtual IGenericRepository Repository
{
get
{
return GetRepository<IGenericRepository>(this.GetType());
}
}
protected virtual T Find<T>(Object id) where T : class
{
return (T)Repository.GetByID<T>(id);
}
}
I'm unsure how to call this find method if I'm only using interfaces, since the current service definition is using concrete classes.
Apologies about this being a long winded post. I've been looking over this for three days, but I need to know what others think of the current set up, and whether I should be using IOC for domain objects in service layer, or whether I should follow the current set up. It just all feels a bit coupled for me at the moment.
There's a lot you're misunderstanding I think.
I'll start with the service structure. You don't have to have each service only handling 1 type of entity, but there's nothing wrong with that as long as it doesn't get in the way of efficiency. Your example is likely unreasonably simplistic, so you probably could have CarService handle Wheel management without any future maintenance issues, but it's common to divide services up by entity and although it often requires some exceptions it usually works fine.
The IoC code you have written is all sorts of wrong though. The goal of IoC is to keep all the code that will be doing your dependency management in a single place that's sort of out of the way. Your code has CarService instantiating WheelService explicitly, while that should be handled by your IoC container. Also, having a GetRepository method is very awkward, and also should be handled automatically by your IoC container.
One way you could setup your services and repositories would be like this (if you're using constructor injection). This is just an example (and a verbose one at that), don't go copying this structure into your own code without fully understanding it.
public interface IRepository {
//Some interfaces
//This method could only really be implemented if you are using an ORMapper like NHibernate
public T FindById<T>(Object id) { }
}
public class BaseRepository : IRepository {
//Some base crud methods and stuff. You can implement this if you're using an ORMapper
public T FindById<T>(Object id)
{
return CurrentSession.FindById<T>(id);
}
}
public class WheelRepository : BaseRepository {
//Wheel crud
//If you don't have an ORMapper because you're a masochist you can implement this here
public Wheel FindById(Object id) { }
}
public class CarRepository : BaseRepository {
//Car crud
//If you don't have an ORMapper because you're a masochist you can implement this here
public Car FindById(Object id) { }
}
public class BaseService {
protected BaseRepository _baseRepository;
//This constructor is automatically called by your IoC container when you want a BaseService
public BaseService(BaseRepository repository)
{
_baseRepository = repository;
}
//More methods
}
public class WheelService : BaseService
{
protected WheelRepository _wheelRepository;
public WheelService(WheelRepository wheelRepo) : base(wheelRepo)
}
public class CarService : BaseService
{
protected WheelService _wheelService;
protected CarRepository _carRepository;
public CarService(WheelService wheelService, CarRepository carRepository)
{
_wheelService = wheelService;
_carRepository = carRepository;
}
}
Since you're using MVP, I assume some kind of WPF/Winforms app, although I suppose you could do a web app as well if you really wanted to make it fit in asp.net. In either case, they both have a single Factory you can configure for creating your presenter classes. In that factory, you'd have it do all the injection there, out of the way in a spot you never have to worry about or even look at after setting it up. That code would just call this:
//Override the default factory method (just made this up)
public override Presenter GetPresenter(Type presenterType)
{
return ComponentFactory.GetInstance(presenterType);
}
Then if you had a presenter that depended on a service, it would automatically be there, and everything that service needs would be there too. Notice how there's no ugly service constructors or factory calls anywhere else. All the dependencies are automagically setup by the container.
I don't know why the code at your company has those awful GetRepository methods. That's an instance of an anti-pattern, because you're replacing what would normally be a constructor call like new Repository() with a GetRepository call instead that's only marginally more maintainable.
You should try playing around with some well-known containers. Structuremap is a pretty good one.
In my solution there's a few WCF services, each of them implementing it's own callback interface. Let's say they are called: Subscribe1, with ISubscribe1 and ICallback1, etc.
It happens there are a few methods shared among ICallbacks, so I made a following interface:
interface ICallback
{
[OperationContract]
void CommonlyUsedMethod();
}
and i inherited it in all: ICallback1 : ICallback, ICallback2 : ICallback, etc. And deleted the CommonlyUsedMethod() from all callback interfaces.
Now, on the service-side code, everything compiles fine and services can start working as usual. But, when I updated the service references for the client, CommonlyUsedMethod() dissapeared from the reference.cs file (the ISubscribeCallback part), and could no longer be used to send data to back to the client.
try to set the ServiceContract attribute on the base interface also.
Ok, this is the exact code, I condensed it as much as I can. Just start a new console application and copy/paste it. Start it and add a service reference to it. CommonlyUsedMethod() is not present in the reference, while the other methods are. Could it be framework 4?
using System;
using System.ServiceModel;
using System.ServiceModel.Description;
namespace TestService
{
class Program
{
static void Main()
{
var serviceHost=new ServiceHost(typeof(Subscribe1), new Uri("net.tcp://localhost:8888"));
serviceHost.Description.Behaviors.Add(new ServiceMetadataBehavior());
serviceHost.AddServiceEndpoint(typeof(ISubscribe1), new NetTcpBinding(SecurityMode.None), string.Empty);
serviceHost.AddServiceEndpoint("IMetadataExchange", MetadataExchangeBindings.CreateMexTcpBinding(), "mex");
serviceHost.Open();
Console.WriteLine("Working!");
while(Console.ReadKey(true).Key!=ConsoleKey.Escape) { }
}
}
[ServiceContract]
interface ICallbackBase
{
[OperationContract]
void CommonlyUsedMethod();
}
[ServiceContract]
interface ICallback1 : ICallbackBase
{
[OperationContract]
void SpecificMethod();
}
[ServiceContract(CallbackContract=typeof(ICallback1))]
interface ISubscribe1
{
[OperationContract]
void TestMethod();
}
[ServiceBehavior]
class Subscribe1 : ISubscribe1
{
[OperationBehavior]
public void TestMethod()
{
}
}
}
Does this reflect what you have in your code?
[ServiceContract]
public interface ICallbackBase
{
[OperationContract]
void CommonlyUsedMethod();
}
[ServiceContract]
public interface ICallback1 : ICallbackBase
{
[OperationContract]
void SpecificMethod();
}
This is essentially the structure I have in my production solution, and then I use the proxies that are generated when I add a Service Reference to access my methods from the client.
For reference, the generated interface then looks like this:
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ServiceModel.ServiceContractAttribute(ConfigurationName="MyNamespace.ICallback1")]
public interface ICallback1 {
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/ICallbackBase/CommonlyUsedMethod", ReplyAction="http://tempuri.org/ICallbackBase/CommonlyUsedMethodResponse")]
void CommonlyUsedMethod();
}
Note the "ICallbackBase" in the OperationContractAttribute - it really does know where the method came from.
I'm not sure that what you are trying to do using WCF is possible. When you use inheritance in WCF you need to apply the KnownType attribute to the DataContract so that the DataContractSerializer will know to serialize it and make it available on the other end. Since you cannot put the KnownType attribute on interfaces, there is no way to tell the serializer that this is needed on the other end. Thus is does not show up when you implement it on the client.