Wcf and Interfaces as Parameters - c#

i have a library with some entities that share the same interface. clients and service share this assembly. now i wonder if there is a way to have this Interface-type as Parameter in my service contracts so that i can use the same method for all classes implementing the interface.
the entities themselve are all decorated with datacontract-attribute and its members with datamember attributes.
is it possible at all? probably with the NetDataContractSerializer?
i know that i can do it with a base class (some abstract class e.g.) and the knowntype-attribute but i´d definitely prefer the Interface as identificator of the objects cause it is used widely in the client app and would ease development.
thanks

I solved the problem using the ServiceKnownType attribute at the implementations of the OperationContracts.
When telling your classes that implement the interface as ServiceKnownType's, you can use the interface as parameter and therefore are able to use all classes implementing your interface as long as they are serializable. (look at "Programming WCF Services" from Juval Löwy, page 100)

It certainly isn't possible under regular "mex". It might be possible with assembly sharing, but I really wouldn't recommend it - you are fighting WCF: it will be brittle, etc. Of course, you can always mask this in your object model - i.e. rather than calling the [OperationContract] method directly, abstract this away into a wrapper method that hides the WCF details (perhaps using different objects for the data transfer than it actually returns).

[I just read your answer and realized that you were asking specifically about parameters to service methods. I'll leave my comments here in case they're still helpful.]
What I've done on projects where I know I have WCF on both sides of the wire, is something like:
A library of only the shared interfaces, eg:
namespace SharedInterfaces {
public interface ICompositeType {
bool BoolValue { get; set; }
string StringValue { get; set; }
}
}
The WCF service library, where the [DataContract]s (POCOs) implement the shared interfaces.
[DataContract]
public class CompositeType : ICompositeType {
bool boolValue = true;
string stringValue = "Hello ";
[DataMember]
public bool BoolValue {
get { return boolValue; }
set { boolValue = value; }
}
[DataMember]
public string StringValue {
get { return stringValue; }
set { stringValue = value; }
}
}
In the service client, each proxy POCO can be "compelled" to implement the shared, deployed, interface using a partial class (it will anyway if svcutil did it's job correctly), and you'll be able to program to the interface in the rest of your client code:
namespace ServiceClient.ServiceReference1 {
public partial class CompositeType : ICompositeType {
}
}
This partial is also useful if you want to add some additional properties or methods that the client can make use of (eg. Presenter or ViewModel concepts in MVP or MVVM patterns).

Related

Library Input Data via Interface

We are having issues with a pattern, that is emerging in our C# solution.
Initial idea:
We have a set of features (mostly calculations), that are needed in several projects. We imagined our solution to be modular - each feature implemented as a class library which can than be referenced as a .dll in other projects.
First Issue:
What happened was, that libraries had classes, that specified the input data needed for doing the math. As a single library could be used in a number of projects we ended up coding mappings for each project, that ported the projects domain objects to the input data classes. This was tedious, as we were mostly doing a one-to-one conversion - the classes were basically the same.
Idea:
We figured that we would solve our problem with using interfaces instead of classes to specify our input data. That way we could simply label our domain classes with interfaces and we wouldn't have to do the mappings anymore.
Current Issue:
We now have a complete mayhem with interface definitions and the use of these interfaces in calculation methods. E.g.
public interface ILevel2Child
{
}
public interface ILevel1Child<TLevel2Child>
where TLevel2Child : ILevel2Child
{
List<TLevel2Child> Children { get; }
}
public interface IParent<TLevel1Child, TLevel2Child>
where TLevel1Child: ILevel1Child<ILevel2Child>
where TLevel2Child: ILevel2Child
{
List<TLevel1Child> Children { get; }
}
When we end up using the IParent interface in a method or interface, we keep dragging these insanely long signatures along.
Questions:
Was our idea of using interfaces bad to begin with?
If not, is something wrong with the way we specify our interfaces?
If still not, is there any way we can stop this insane signature pattern?
Additional explanation:
We started with
public interface ILevel2Child
{
}
public interface ILevel1Child
{
List<ILevel2Child> Children { get; }
}
public interface IParent
{
List<ILevel1Child> Children { get; }
}
but that prevented us from doing
public class Level2Child : ILevel2Child
{
}
public class Level1Child : ILevel1Child
{
List<Level2Child> Children { get; }
}
public class Parent : IParent
{
List<Level1Child> Children { get; }
}
and that was not acceptable.

Class derived from generic type for template some bunch of property

In my project I try separate domain model from DAO like in example from https://vaughnvernon.co/?p=879 . I use for it class which backend state of my domain object which is internal and only use in repository. Next i have my domain object and i want to generic some logic for use it. There is a code:
public abstract class GenericEntity<T> where T : class
{
protected readonly T _state;
internal GenericEntity(T state)
{
_state = state;
}
internal T State
{
get
{
return _state;
}
}
}
and I want to derived from this class, but my domain model should be public and I cant do that cause of internal DAOEntity.
public class DomainModel : GenericEntity<DAOEntity>
{
}
internal class DAOEntity
{
}
It is some walk around to it? Or i need to implement this code to manage state in all my class. I dont want to either make some base DAOEntity cause then i need to cast it in all domain models.
EDIT:
Maybe you dont understand my question. Right now i have code which look like Marcos Jonatan Suriani show in his answer:
public class Product
{
public Product()
{
State = new ProductState();
}
internal Product(ProductState state)
{
State = state;
}
}
public class ProductState
{
}
public class AgilePMContext : DbContext
{
public DbSet<ProductState> Products { get; set; }
}
But I'm looking for some design pattern where i could reduce copy paste code with my internal state implementation, so i want to go depper with this solution, cause when i have many domain model this is a code which I need reapet in all.
public class DomainModel : GenericEntity<DAOEntity>
{
}
This is backwards - you've written a domain model that depends on the data model. You want this dependency to go the other way around: the data model should depend on the domain model.
In a sense, what Vaughn is telling you is that the domain model defines interfaces for data service providers, and the data model implements those providers.
For example, consider a simplified model for banking
class DepositModel : BankingApi.Deposit {
void depositFunds(Account account, Deposit deposit, Clock clock) {
AccountId currentAccount = account.id();
AccountId depositInto = deposit.accountId();
assert depositInto.equals(currentAccount);
Money amount = deposit.amount();
account.deposit(amount);
Time processedAt = clock.now();
TransactionId transactionId = deposit.transactionId();
account.updateTransactionHistory(transactionId, processedAt)
}
}
Observe that the model doesn't touch primitive data. All of the state manipulations are hidden by the value types.
That means your data model can implement structure the data any way you like, and manipulate it in any way that satisfies the specification.
The article purposes a slightly different solution. The main purpose of the pattern is to focus on the Domain Core and avoid workarounds, specially when mapping the domain object to relational (ORM, for ie).
Taking this approach will help us to stay focused on what really
counts the most, our Core Domain and its Ubiquitous Language.
The approach is to have the domain as ubiquitous as it can be by providing state objects - that is going to be used by the ORM (EF). So, the business rules remain on Domain objects and ORM related go to State objects.
One approach uses a Separated Interface with an implementation class, and the other uses a domain object backed by a state object.
Your implementation should be composed by interfaces that represents the domain (IProduct, for instance):
We create an interface that we want our client to see and we hide the implementation details inside the implementing class.
And also composed by two implementations of the interfaces; one for the Domain object (Product), and another for the state object (ProductState). The domain implementation should have two constructors:
a public business constructor for normal clients and a second internal constructor that is used only by internal implementation components.
interface IProduct
{
}
public class Product : IProduct
{
public Product()
{
State = new ProductState();
}
internal Product(ProductState state)
{
State = state;
}
}
public class ProductState: IProduct
{
}
public class AgilePMContext : DbContext
{
public DbSet<ProductState> Products { get; set; }
}

How to make readonly property in WCF? [duplicate]

I have a server side class which I make available on the client side through a [DataContract]. This class has a readonly field which I'd like to make available through a property. However, I'm unable to do so because it doesn't seem that I'm allowed to add a [DataMember] property without having both get and set.
So - is there a way to have a [DataMember] property without setter?
[DataContract]
class SomeClass
{
private readonly int _id;
public SomeClass() { .. }
[DataMember]
public int Id { get { return _id; } }
[DataMember]
public string SomeString { get; set; }
}
Or will the solution be use the [DataMember] as the field - (like e.g. shown here)? Tried doing this too, but it doesn't seem to care the field is readonly..?
Edit: Is the only way to make a readonly property by hacking it like this? (no - I don't want to do this...)
[DataMember]
public int Id
{
get { return _id; }
private set { /* NOOP */ }
}
Your "server-side" class won't be "made available" to the client, really.
What happens is this: based on the data contract, the client will create a new separate class from the XML schema of the service. It cannot use the server-side class per se!
It will re-create a new class from the XML schema definition, but that schema doesn't contain any of the .NET specific things like visibility or access modifiers - it's just a XML schema, after all. The client-side class will be created in such a way that it has the same "footprint" on the wire - e.g. it serializes into the same XML format, basically.
You cannot "transport" .NET specific know-how about the class through a standard SOAP-based service - after all, all you're passing around are serialized messages - no classes!
Check the "Four tenets of SOA" (defined by Don Box of Microsoft):
Boundaries are explicit
Services are autonomous
Services share schema and contract, not class
Compability is based upon policy
See point #3 - services share schema and contract, not class - you only ever share the interface and XML schema for the data contract - that's all - no .NET classes.
put DataMember attribute on a field not the property.
Remember thought, that WCF does not know encapsulation. Encapsulation is a OOP term, not a SOA term.
That said, remember that the field will be readonly for people using your class - anyone using the service will have full access to the field on their side.
I had some properties in a class in my service layer I wanted to pass over to Silverlight. I didn't want to create a whole new class.
Not really 'recommended', but this seemed the lesser of two evils to pass over the Total property to silverlight (solely for visual databinding).
public class PricingSummary
{
public int TotalItemCount { get; set; } // doesnt ideally belong here but used by top bar when out of store area
public decimal SubTotal { get; set; }
public decimal? Taxes { get; set; }
public decimal Discount { get; set; }
public decimal? ShippingTotal { get; set; }
public decimal Total
{
get
{
return + SubTotal
+ (ShippingTotal ?? 0)
+ (Taxes ?? 0)
- Discount;
}
set
{
throw new ApplicationException("Cannot be set");
}
}
}
There is a way to achieve this. But be warned that it directly violates the following principle cited in this answer:
"3. Services share schema and contract, not class."
If this violation does not concern you, this is what you do:
Move the service and data contracts into a separate (portable) class library. (Let's call this assembly SomeService.Contracts.) This is how you'd define an immutable [DataContract] class:
namespace SomeService.Contracts
{
[DataContract]
public sealed class Foo
{
public Foo(int x)
{
this.x = x;
}
public int X
{
get
{
return x;
}
}
[DataMember] // NB: applied to the backing field, not to the property!
private readonly int x;
}
}
Note that [DataMember] is applied to the backing field, and not to the corresponding read-only property.
Reference the contract assembly from both your service application project (I'll call mine SomeService.Web) and from your client projects (mine is called SomeService.Client). This might result in the following project dependencies inside your solution:
Next, when you add the service reference to your client project, make sure to have the option "reuse types" enabled, and ensure that your contract assembly (SomeService.Contracts) will be included in this:
Voilà! Visual Studio, instead of generating a new Foo type from the service's WSDL schema, will reuse the immutable Foo type from your contract assembly.
One last warning: You've already strayed from the service principles cited in that other answer. But try not to stray any further. You might be tempted to start adding (business) logic to your data contract classes; don't. They should stay as close to dumb data transfer objects (DTOs) as you can manage.
Define the Service contract (Interface) Before implementing the contract using the class.

Is it possible to contrain a class from a third-party web service?

I have a two classes where 1 is inherited. There are a number of other classes similar to Acme123Response with different response classes. I.e. ApplicationInfo.
ApplicationInfo belongs to a third-party web service. The question is, is it possible to add a where constraint to BuyerResponse given that ApplicationInfo and the rest are outside of my immediate control?
public class Acme123Response : BuyerResponse<ApplicationInfo>
{
public Acme123Response(ApplicationInfo response)
: base(response)
{
}
}
public abstract class BuyerResponse<T> : ResponseBase
{
readonly T _response;
protected T Response
{
get { return _response; }
}
protected BuyerResponse(T response)
{
_response = response;
// Do something else
}
}
If I understood your comments correctly, then your question is can you define a base interface for classes defined in 3rd party assemblies. AFAIK this isn't possible (even if you could fork the source it's not something I'd want to do): the best I'd think you can do is define wrapper classes/adapters that implement your unifying interface, and then base your generic constraint on that.
This also has the effect of shielding your own implementations from 3rd party classes with an interface, which is generally something you'd want to do anyways.

When do I use abstract classes versus interfaces with regards to dependency Injection?

I have been reading some articles about the SOLID principles and dependency Inversion. From my point of view, I must use an interface to talk to any class. My classes are chatting by using interfaces.
First Question:
I am using an abstract class but for the second part of my code, I use an Interface.
Usage1
namespace DependencyInjection
{
public interface IMessage
{
}
public abstract class Message
{
public abstract void Get();
public abstract void Send();
}
public class Sms : Message, IMessage
{
public override void Get()
{
Console.WriteLine("Message Get!");
}
public override void Send()
{
Console.WriteLine("Message Send!");
}
}
public class MessageManager
{
private IMessage _message;
public Sms Sms
{
get { return _message as Sms; }
set { _message = value; }
}
public MessageManager(IMessage message)
{
_message = message;
}
}
}
Usage:
class Program
{
static void Main(string[] args)
{
MessageManager msg = new MessageManager(new Sms());
msg.Sms.Get();
msg.Sms.Send();
Console.Read();
}
}
Usage2
namespace DependencyInjection
{
public interface IMessage
{
public void Get();
public void Send();
}
public class Sms : IMessage
{
public void IMessage.Get()
{
Console.WriteLine("Message Get!");
}
public void IMessage.Send()
{
Console.WriteLine("Message Send!");
}
}
public class MessageManager
{
private IMessage _message;
public Sms Sms
{
get { return _message as Sms; }
set { _message = value; }
}
public MessageManager(IMessage message)
{
_message = message;
}
}
}
What is the difference between Usage1 and usage2? When do I choose usage1 or Usage2?
Abstract classes here to fight with duplicated code. Interfaces - to define contracts (API).
Depend on interfaces - they simply describe contract (API) of dependency, and they can by mocked easily. So, start with interface:
public interface IMessage
{
void Get(); // modifiers like public are not allowed here
void Send();
}
And here is your dependent class, which should depend only on abstraction (i.e. interface):
public class MessageManager
{
private IMessage _message;
// depend only on abstraction
// no references to interface implementations should be here
public IMessage Message
{
get { return _message; }
set { _message = value; }
}
public MessageManager(IMessage message)
{
_message = message;
}
}
Then create class, which will implement your interface:
public class Sms : IMessage
{
// do not use explicit implementation
// unless you need to have methods with same signature
// or you want to hide interface implementation
public void Get()
{
Console.WriteLine("Message Get!");
}
public void Send()
{
Console.WriteLine("Message Send!");
}
}
Now you have inversed dependencies - MessageManager and Sms depend only on IMessage. You can inject any IMessage implementations to MessageManager (MessageManager now fit OCP - open for extension, but closed for modification).
Create base abstract message class only when you have duplicated code in several IMessage implementors. When you create abstract class (place, where you move duplicated code), you should not change interface, because contract stays the same. Just inherit your base class from original IMessage interface.
The original definition of an interface is an abstract class with all pure virtual methods (i.e. abstract methods), this was how you describe an interface in C++. If you are not creating virtual functions with default definitions then you really do not need an abstract class at all. If you do have some default functionality that you would like the children of your Message class to inherit (and allow to override or not) then you would use an abstract class. An abstract class can also define protected methods and/or properties and fields, these can be used by classes that inherit from the abstract class but not by classes that use the abstract class. All methods in an interface would be public. In the case you laid out an interface would be fine.
based on what I see you aren't really using an interface at all. Sure you implement the methods, but the consuming class shouldn't really know or even care about the implementation. Therefore, you shouldn't really see any reference or casting to Sms. You should be using a IoC framework such as Unity, Ninject, structuremap. If you actually need a public property returning an IMessage, it should return IMessage and not Sms, whether you should be doing that is a different conversation.
That said, the first Usage doesn't have anything in the IMessage so it is worthless. Also, I often use an abstract / base class to handle common functionality between multiple implementations of an interface. In you scenario, there is no need for the abstract class. The only time I create abstract methods without any code is if the abstract class actually fires that method in some capacity but expects the derived class to implement the functionality.
Anyway, to answer you question Usage #2 seems closer to the correct solution, but just remove the references to Sms and let an IoC container handle that.
An interface does not contain any implementation code and does not force the implementer to derive its implementation form a given class. A base class (abstract or not) can already contain some logic. This can be an advantage as well as an undesirable constraint.
Of course you can combine both approaches. Define and program against an interface and at the same time provide a base class (or several base classes) implementing this interface and proving some basic logic that simplifies an implementers task. A person implementing the interface can decide to go the easy way and to extend a base class or to create something completely new and implement the interface directly.
The .NET Framework class library provides base classes for collections like Collection<T> or KeyedCollection<TKey,TItem> both implementing IList<T> that you can use as a base for creating your own specialized collection. But of course you can start from scratch and implement IList<T> directly.
The reason to choose an abstract class over an interface has to do with reusable code. The fact that you're using dependency injection doesn't change this answer.
Do all of the subclasses have common functionality? If so, it can be defined in the base class.
Should the template method design pattern be used? If so, the algorithm exists in the base class.
As always, the answer is: "It depends." You can't do these approaches with interfaces as interfaces only specify the contract and don't have implementation. If the contract is all you need, then go with an interface. If you need code to be shared by the subclasses, then go with an abstract class.
I don't have a lot to add to the other answers provided, apart from some reasons to listen to them:
An abstract class with only abstract methods is essentially an interface. The difference is that it could have some form of virtual implementation, and therein lies the trap: its all too easy when trying to reduce duplication using a base class to hide dependencies.
Let's say you have a set of objects which need to persist between runs. It's tempting to add a save functionality to the base class so that no one else has to worry about how the save works. The problem is, if you totally hide it, you create a testing nightmare where the implementation has to be tested, or else a lot of functionality is relegated to only integration testing. Using Strategy for the save functionality would totally resolve the issue, and the two can be combined simply enough.
The problem is more temptation than one simply being bad. Inheritance does not stop DI, but it doesn't encourage it either. If you're trying to get into SOLID and DI, you may be better off avoiding inheritance for now.

Categories

Resources