I have the following interfaces defined:
public interface IAudit {
DateTime DateCreated { get; set; }
}
public interface IAuditable {
IAudit Audit { get; set; }
}
The IAuditable interface says which classes I will have an Audit for. The IAudit interface is the actual Audit for that class. For example say I have the following implementations:
public class User : IAuditable {
public string UserName { get; set; }
public UserAudit Audit { get; set; }
}
public class UserAudit : IAudit {
public string UserName { get; set; }
public DateTime DateCreated { get; set; }
public UserAdit(User user) {
UserName = user.UserName;
}
}
Now given an object which is IAuditable (User from above), I'd like to be able to create an intance of IAudit (UserAdit from above) by feeding in the IAuditable object into the constructor. Ideally i'd have something like:
if (myObject is IAuditable) {
var audit = new IAudit(myObject) { DateCreated = DateTime.UtcNow }; // This would create a UserAudit using the above example
}
However I have a bunch of problems:
- You can't create an instance of an interface
- No where in the code does it define which
IAuditapplies to whichIAuditable - I can't specify that the
IAuditinterface must have a constructor which takes anIAuditable
I'm sure this is a design pattern many have had before but I can't get my head around it. I'd really appreciate if someone could show me how this can be achieved.