S
S
saxer2015-09-23 15:18:15
ASP.NET
saxer, 2015-09-23 15:18:15

How to create an interface that would implement its constructor in an object?

How do I use an interface to implement a constructor in an object?
For example, I have an object whose methods all use the user ID:

public interface ILogic
{
void Add(int userId);
void Change(int userId);
}

public class logic: ILogic
{
public void add(int userId)
{
....
}
public void change (int userId)
{
....
}
}

It is logical to define a constructor in the class so that when creating an object, request userId
public class logic
{
private int _userId;
public logic(int userId)
{
_userId = userId
}
public void add()
{
// ... делаем что либо используя _userId
}
public void change()
{
// ... делаем что либо используя _userId
}
}

How can I change the interface so that it takes into account that there must be a constructor in the class that implements it?
I had this question when using ninject.
For example, I have an Order class in all its methods uses int userId (to implement logging).

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Kovalsky, 2015-09-23
@saxer

An interface is simply a class promise that it has "methods like this" with "like this signature". What is your problem? In theory:

public interface ILogic
{
void Add();
void Change();
}

And in a specific implementation, do what you want, read from wherever you want.
The class will have a constructor in any case. There are no classes without a constructor.
UPD: Something like this. The code is written on the knee and may have bugs. The main thing is the idea
public class someClass
{
private int _someParametr;
private someClass(){}
public static SomeClass CreateInstance(int inputParam)
{
var t = new SomeClass(){_someParametr = inputParam};
return t;
}
}

habrahabr.ru/post/235995 - Read, you can find useful thoughts.

S
Sergey, 2015-09-23
@sergey_kzn

Make a property in the interface. Or write an abstract class with the necessary constructors and methods.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question