I have solved my problem in the way I will describe below but I want to find the best way.
Typescript has generic type Readonly that solved this problem.
Thanks for your suggests I used folowing codes (.net6) :
public interface IReadOnlyAbility
{
bool IsReadOnly { get; }
void ReadOnly();
public T CheckForSetValue<T>(T PropertyValue)
{
if (IsReadOnly)
throw new ReadOnlyException();
return PropertyValue;
}
}
public interface IUser : IReadOnlyAbility
{
string UserName { get; set; }
string Password { get; set; }
}
public class User : IUser
{
private string userName = string.Empty;
private string password = string.Empty;
public bool IsReadOnly { get; private set; }
public string UserName
{
get => userName;
set => userName = CheckForSetValue(value);
}
public string Password
{
get => password;
set => password = CheckForSetValue(value);
}
protected T CheckForSetValue<T>(T Value) => ((IReadOnlyAbility)this).CheckForSetValue(Value);
public void ReadOnly() => IsReadOnly = true;
}
Then I added dependency injection >>> Services.AddTransient<IUser, User>();
Now , I used it :
var user = Services.GetService<IUser>();
user.UserName = "UserName";
user.Password = "Password";
user.ReadOnly();
Useris not a service you'd register through DI -- normally. Such classes can also be built asrecords (record User(string Username, string Password)) or using custominitproperties, either of which give you instances that are immutable from the time of creation. Such instances can also be built by builder classes that are themselves not immutable (those would be a better candidate for DI, if there's at all a case for exchanging their implementation).